Using the Java Mapper Framework for App Engine

The recently released Mapper framework is the first part of App Engine’s mapreduce offering. In this post, we’ll be discussing some of the types of operations we can perform using this framework and how easily they can be done.

Introduction to Map Reduce

If you aren’t familiar with Map Reduce, read more about it from a high level from Wikipedia here. The official paper can be downloaded from this site if you’re interested in a more technical discussion.

The simplest breakdown of MapReduce is as follows:

  1. Take a large dataset and break it into pieces, mapping individual pieces of data
  2. Work on those mapped datasets and reduce them into the form you need

A simple example here is full text indexing. Suppose we wanted create indexes from existing text documents. We would use the Map step to iterate over every document and “map” each phrase or term to a document, then we would “reduce” the mappings by writing them to an index. Map/reduce problems have the advantage of not only being easy to conceptualize as problems that can be distributed and parallelized, but also because there are frameworks that support many of the administrative functions of map-reduce: failure recovery, distribution of work, tracking status of jobs, reporting and so forth. The appengine-mapreduce project seeks to provide as many of these features as possible while making it as easy as possible for developers to write large batch processing jobs without having to think about the plumbing details.

But I only have Map available!

Yes, this is true  – as of the writing of this post, only the “map” step exists, hence why it’s currently referred to as the “Mapper API”. That doesn’t mean it’s not useful. For starters, it is a very easy way to perform some operation on every single Entity of a given Kind in your datastore in parallel. What would you have to build for yourself if Mapper weren’t available?

  1. Begin querying over every Entity in chained Task Queues
  2. Store beginning and end cursors (introduced in 1.3.5)
  3. Create tasks to work with chunks of your datastore
  4. Write the code to manipulate your data
  5. Build an interface to control your batch jobs
  6. Build a callback system for your multitudes of parallelized workers to call when the entire task has completed

It’s certainly not a trivial amount of work. Some things you can do very easily with the Mapper library include:

  • Modify some property or set of properties for every Entity of a given Kind
  • Delete all entities of a single Kind – the functional equivalent of a “DROP TABLE” if you were using a relational database
  • Count the occurrences of some property across every single Entity of a given Kind in your datastore

We’ll go through a few of these examples in this post.

Our Sample application

Our sample application will be a modified version of the Guestbook demo. We’ll add a few additional properties. For simplicity, we’ll use the low-level API, since the Mapper API also uses the low-level API. You can see this application here:http://ikai-mapper-demo.appspot.comThe code is also available to clone via Github if you’d like to follow along.

How to define a Mapper

There are three steps to defining a Mapper:

  1. Download, build and place the appengine-mapreduce JAR files in your WEB-INF/lib directory and add them to your build path. You only need to do this once per project. The steps for doing this are on the “Getting Started” page for Java. You’ll need all the JAR files that are built.
  2. Make sure that we have a DESCENDING index created on Key. This is important! If we run our Mapper locally, this’ll automatically be created in our datastore-indexes.xml file when we deploy our application. One trick to ensure that indexes get built before they are needed, at least in a live application, is to create and deploy an application with the new index configuration to a non-default version. Because all versions use the same datastore and the same set of indexes, this will schedule the index to be built before we need it in the live version. When it has completed, we simply switch the default version over, and we’re ready to roll.
  3. Create your Mapper class
  4. Configure your Mapper class in mapreduce.xml

We’ll go over steps 3 and 4 in each example.

Example 1: Changing a property on every Entity (Naive way)

(You can even use this technique if you just need to change a property on a large set of Entities).

Assuming you’ve already set up your environment for the Mapper servlet, you can dive right in. Let’s create a Mapper classes that goes through every Entity of a given Kind and converts the “comment” property to use all lowercase letters. We’ll also add a timestamp for when we modified this Entity. In this first example, we’ll do this the naive way. This is a very good way to introduce you to very simple mutations on all your Entities using Mapper.

Note that this requires some familiarity with the Low-Level API. Don’t worry – entities edited or saved using the low-level API are accessible via managed persistence interface such as JDO/JPA (and vice versa). If you aren’t familiar with the low-level API, you can read more about it here on the Javadocs.

The first thing we’ll have to do is define a Mapper. We tried as much as possible to mimic Hadoop’s Mapper class. We’ll be subclassing AppEngineMapper, which is itself a subclass of Hadoop’s Mapper. The meat of this class is the map() method, which we’ll be overriding. We’ll also override the taskSetup() lifecycle callback. We’ll be using this to initialize our DatastoreService, though we could probably initialize it in the body of the map() method itself. The other methods are taskCleanup(), setup() and cleanup() – examples here. Let’s have a look at our code below:

package com.ikai.mapperdemo.mappers;
 
import java.util.Date;
import java.util.logging.Logger;
 
import org.apache.hadoop.io.NullWritable;
 
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.tools.mapreduce.AppEngineMapper;
 
/**
 *
 * This mapper changes all Strings to lowercase Strings, sets
 * a timestamp, and reputs them into the Datastore. The reason
 * this is a "Naive" Mapper is because it doesn't make use of
 * Mutation Pools, which can do these operations in batch instead
 * of individually.
 *
 * @author Ikai Lan
 *
 */
public class NaiveToLowercaseMapper extends
        AppEngineMapper<Key, Entity, NullWritable, NullWritable> {
    private static final Logger log = Logger
            .getLogger(NaiveToLowercaseMapper.class.getName());
 
    private DatastoreService datastore;
 
    @Override
    public void taskSetup(Context context) {
        this.datastore = DatastoreServiceFactory.getDatastoreService();
    }
 
    @Override
    public void map(Key key, Entity value, Context context) {
        log.info("Mapping key: " + key);
 
        if (value.hasProperty("comment")) {
            String comment = (String) value.getProperty("comment");
            comment = comment.toLowerCase();
            value.setProperty("comment", comment);
            value.setProperty("updatedAt", new Date());
 
            datastore.put(value);
 
        }
    }
}

Notice that this map method takes 3 parameters:

Key key – this is the datastore Key for the Entity we are about to perform an operation on. Mostly this exists for API compatibility with Hadoop, but we don’t really need it yet. For iterating over datastore Entities, we don’t really need this, because we *could* use this to look up the Entity, but we don’t have to because …

Entity value – … because we actually get the Entity already. If we did a lookup for the Entity, we’d double the amount of lookups we do per Entity. We can certainly use the Key to do a lookup using a PersistenceManager or EntityManager and have a populated, typesafe Entity object, but from an efficiency standpoint we’d be doubling our work for some JDO/JPA sugar.

Context context – We don’t need this in our example, but it’s easy to think of the Context as giving us access to “global” values such as temporary variables and configuration files. For a later example in this post, we’ll be using the Context to store a global value in a counter and increment it. For this example, it’s unused.

If you’re familiar at all with the low-level API, this will look very straightfoward (again, I highly encourage you to read the docs). We take an entity, add 2 properties to it, then re-put() the Entity back into the datastore.

Now let’s add this job to mapreduce.xml:

<configurations>
  <configuration name="Naive Mass toLowercase()">
    <property>
      <name>mapreduce.map.class</name>
 
      <!--  Set this to be your Mapper class  -->
      <value>com.ikai.mapperdemo.mappers.NaiveToLowercaseMapper</value>
    </property>
 
    <!--  This is a default tool that lets us iterate over datastore entities -->
    <property>
      <name>mapreduce.inputformat.class</name>
      <value>com.google.appengine.tools.mapreduce.DatastoreInputFormat</value>
    </property>
 
    <property>
      <name human="Entity Kind to Map Over">mapreduce.mapper.inputformat.datastoreinputformat.entitykind</name>
      <value template="optional">Comment</value>
    </property>
  </configuration>
</configurations>

It looks complex, but it’s really not. We define a configuration element and name the job. The name of the job is also the name we’ll see in the GUI when we fire off the job. We need 3 sets of property elements under this element, which are just name/value pairs. Let’s go over each one we used:

Name: mapreduce.map.class
Value: com.ikai.mapperdemo.mappers.NaiveToLowercaseMapper
This one is straightforward – we provide the name of an AppEngineMapper subclass with the map() method we want run.

Name: mapreduce.inputformat.class
Value: com.google.appengine.tools.mapreduce.DatastoreInputFormat
This is a class that takes some input to map over. DatastoreInputFormat is provided by appengine-mapreduce, but it is possible for us to define our own input formatter. For guidance, check out the source of DatastoreInputFormat here.

In a more advanced example (ahem, future blog post), we’ll discuss building our own InputFormat to read from another source such as the Blobstore. For our examples in this post, we won’t need anything beyond DatastoreInputFormat.

Name: mapreduce.mapper.inputformat.datastoreinputformat.entitykind
Value: Comment
This input is specific to DatastoreInputFormat. It tells DatastoreInputFormat which Entity Kind to iterate over. Note that in the mapper console, a user can type in the name of a Kind or edit this Field to reflect the value they want. We can’t leave this blank, though, if we want this to work.

“Running jobs” appears when we click “Run”. We can click “Detail” to see the progress of our job, or we can “Abort” to quit the job. Note that aborting a job won’t revert our Entities! We’ll end up with a partially run job if we run a giant mutation, so we’ll have to be cognizant of this when we use this tool.

When the job completes, we’ll take a look at our Comments. Sure enough, they are now all lowercase.

Example 2: Changing a property on every Entity using Mutation Pools

There’s a reason the Mapper in Example 1 is called a Naive Mapper: because it doesn’t take advantage of mutation pools. As we all know, App Engine’s datastore is capable of handling operations in parallel using batched calls. We’re already doing work in parallel by specifying shards, but we’ll want to use batched calls when possible. We do this by adding the mutations we want to a mutation pool, then, periodically as the pool hits a certain size, we flush all the writes to the datastore with a single call instead of individually. This has the advantage of making our map() call as fast as possible, since all we’re really doing is making a list of operations to perform all at once when the system is good and ready. Let’s define the XML file first assuming we call the class PooledToLowercaseMapper:

<configuration name="Mass toLowercase() with Mutation Pool">
  <property>
    <name>mapreduce.map.class</name>
 
    <!--  Set this to be your Mapper class  -->
    <value>com.ikai.mapperdemo.mappers.PooledToLowercaseMapper</value>
  </property>
 
  <!--  This is a default tool that lets us iterate over datastore entities -->
  <property>
    <name>mapreduce.inputformat.class</name>
    <value>com.google.appengine.tools.mapreduce.DatastoreInputFormat</value>
  </property>
 
  <property>
    <name human="Entity Kind to Map Over">mapreduce.mapper.inputformat.datastoreinputformat.entitykind</name>
    <value template="optional">Comment</value>
  </property>
 
</configuration>

It looks almost exactly the same. That’s because the meat is in what we do in the actually class itself:

package com.ikai.mapperdemo.mappers;
 
import java.util.Date;
import java.util.logging.Logger;
 
import org.apache.hadoop.io.NullWritable;
 
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.tools.mapreduce.AppEngineMapper;
import com.google.appengine.tools.mapreduce.DatastoreMutationPool;
 
/**
 *
 * The functionality of this is exactly the same as in {@link NaiveToLowercaseMapper}.
 * The advantage here is that since a {@link DatastoreMutationPool} is used, mutations
 * can be done in batch, saving API calls.
 *
 * @author Ikai Lan
 *
 */
public class PooledToLowercaseMapper extends
        AppEngineMapper<Key, Entity, NullWritable, NullWritable> {
    private static final Logger log = Logger
            .getLogger(PooledToLowercaseMapper.class.getName());
 
    @Override
    public void map(Key key, Entity value, Context context) {
        log.info("Mapping key: " + key);
 
        if (value.hasProperty("comment")) {
            String comment = (String) value.getProperty("comment");
            comment = comment.toLowerCase();
            value.setProperty("comment", comment);
            value.setProperty("updatedAt", new Date());
 
            DatastoreMutationPool mutationPool = this.getAppEngineContext(
                    context).getMutationPool();
            mutationPool.put(value);
        }
    }
}

Aha! So we finally put the context to use. Granted, we use the context as a parameter to another, more useful method, but at least we’re using it.  We acquire a DatastoreMutationPool using the getAppEngineContext(context).getMutationPool() method, then we just call put() and pass the changed entity. DatastoreMutationPool is defined here and is open source.

The interface is similar to that of DatastoreService. There’s not a lot of fancy stuff going on here. put(), as we’ve seen, is defined. get() isn’t, because, well, that method makes no sense in this context. delete() is defined, which brings me to my bonus section:

Bonus Example 2: Delete all Entities of a given Kind

One of the most common questions asked in the group is, “How do I drop table?” Usually, this question is asked by new App Engine developers who don’t yet understand that the datastore is a distributed key-value store and not a relational database. But it’s also a legitimate use case. What if you just wanted to nuke all Entities of a given Kind? Prior to Mapper, you would have had to write your own handler to take care of this. Mapper makes this very easy. Here’s what a generic “DeleteAllMapper” would look like. This will work with *any* Entity Kind:

package com.ikai.mapperdemo.mappers;
 
import java.util.logging.Logger;
 
import org.apache.hadoop.io.NullWritable;
 
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.tools.mapreduce.AppEngineMapper;
import com.google.appengine.tools.mapreduce.DatastoreMutationPool;
 
/**
 *
 * This Mapper deletes all Entities of a given kind. It simulates the
 * DROP TABLE functionality asked for by developers.
 *
 * @author Ikai Lan
 *
 */
public class DeleteAllMapper extends
        AppEngineMapper<Key, Entity, NullWritable, NullWritable> {
    private static final Logger log = Logger.getLogger(DeleteAllMapper.class
            .getName());
 
    @Override
    public void map(Key key, Entity value, Context context) {
        log.info("Adding key to deletion pool: " + key);
        DatastoreMutationPool mutationPool = this.getAppEngineContext(context)
                .getMutationPool();
        mutationPool.delete(value.getKey());
    }
}

That’s it! We wire it up the same way we wire up other Mappers:

<configuration name="Delete all Entities">
  <property>
    <name>mapreduce.map.class</name>
 
    <!--  Set this to be your Mapper class  -->
    <value>com.ikai.mapperdemo.mappers.DeleteAllMapper</value>
  </property>
 
  <!--  This is a default tool that lets us iterate over datastore entities -->
  <property>
    <name>mapreduce.inputformat.class</name>
    <value>com.google.appengine.tools.mapreduce.DatastoreInputFormat</value>
  </property>
 
  <property>
    <name human="Entity Kind to Map Over">mapreduce.mapper.inputformat.datastoreinputformat.entitykind</name>
    <value template="optional">Comment</value>
  </property>
</configuration>

Get the code

You’re undoubtedly ready to start playing with this thing. You’ve got everything you need to know. First, here’s the getting started page for appengine-mapreduce in Java:

Here’s my sample source code on GitHub.

Summary

So there you have it: an easy to use tool for mapping operations across entire Entity Kinds. There are still a lot of topics to cover, and we’ll likely explore them in a future article. For instance, I didn’t have a chance to cover building your own InputFormat class. We’re still hard at work extending this framework (such as the “Shuffle” and “Reduce” phases), so please post your feedback in the App Engine groups or file bugs in the issue tracker.

About the author

I'm Ikai and I've been fascinated by technology since before I could walk. I became the 'go to' guy for my friend's tech issues and after getting the same questions over and over, I decided to write down my answers. I hope you find the same value that my friend did.

Leave a Comment