Using Cloud Datastore

You can use Google Cloud Datastore to store application data from your App Engine app. Cloud Datastore is a database built for automatic scaling, high performance, and ease of application development.

This document describes how to use the Google Cloud Client Library to store and retrieve data using Cloud Datastore in an App Engine app.

Prerequisites and setup

Follow the instructions in "Hello, World!" for Java on App Engine to set up your environment and project, and to understand how Java apps are structured in App Engine. Write down and save your project ID, because you will need it to run the sample application described in this document.

Clone the repository

Download (clone) the sample:

$ git clone https://github.com/GoogleCloudPlatform/java-docs-samples
$ cd java-docs-samples/flexible/datastore

Edit project configuration and set dependencies

In pom.xml, set dependencies that allow you to use Cloud Datastore:

<dependency>
  <groupId>com.google.cloud</groupId>
  <artifactId>google-cloud-datastore</artifactId>
  <version>0.6.0</version>
</dependency>

Application code

The sample application logs, retrieves, and displays visitor IPs. You can see that a log entry is a simple two-field class that is given the type visit, and is saved to Cloud Datastore using the datastore add() command. Then, the ten most recent visits are retrieved in descending order, using the datastore run() command.

@SuppressWarnings("serial")
@WebServlet(name = "datastore", value = "")
public class DatastoreServlet extends HttpServlet {

  @Override
  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException,
      ServletException {
    // store only the first two octets of a users ip address
    String userIp = req.getRemoteAddr();
    InetAddress address = InetAddress.getByName(userIp);
    if (address instanceof Inet6Address) {
      // nest indexOf calls to find the second occurrence of a character in a string
      // an alternative is to use Apache Commons Lang: StringUtils.ordinalIndexOf()
      userIp = userIp.substring(0, userIp.indexOf(":", userIp.indexOf(":") + 1)) + ":*:*:*:*:*:*";
    } else if (address instanceof Inet4Address) {
      userIp = userIp.substring(0, userIp.indexOf(".", userIp.indexOf(".") + 1)) + ".*.*";
    }

    Datastore datastore = DatastoreOptions.getDefaultInstance().getService();
    KeyFactory keyFactory = datastore.newKeyFactory().setKind("visit");
    IncompleteKey key = keyFactory.setKind("visit").newKey();

    // Record a visit to the datastore, storing the IP and timestamp.
    FullEntity<IncompleteKey> curVisit = FullEntity.newBuilder(key)
        .set("user_ip", userIp).set("timestamp", DateTime.now()).build();
    datastore.add(curVisit);

    // Retrieve the last 10 visits from the datastore, ordered by timestamp.
    Query<Entity> query = Query.newEntityQueryBuilder().setKind("visit")
        .setOrderBy(StructuredQuery.OrderBy.desc("timestamp")).setLimit(10).build();
    QueryResults<Entity> results = datastore.run(query);

    resp.setContentType("text/plain");
    PrintWriter out = resp.getWriter();
    out.print("Last 10 visits:\n");
    while (results.hasNext()) {
      Entity entity = results.next();
      out.format("Time: %s Addr: %s\n", entity.getDateTime("timestamp"),
          entity.getString("user_ip"));
    }
  }
}

Using index.yaml files

The sample app performs simple queries. More elaborate Datastore queries require one or more indexes, which you must specify in an index.yaml file that you upload along with your app. This file may be created manually, or generated automatically while testing your app locally.

For more information

For complete information on Cloud Datastore, including optimizations and concepts, see the Cloud Datastore documentation.

Send feedback about...

App Engine flexible environment for Java docs