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 Ruby on App Engine to set up your environment and project, and to understand how Ruby 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/ruby-docs-samples/
$ cd ruby-docs-samples/appengine/datastore

Edit project configuration and set dependencies

In Gemfile, include the gcloud library, which has the functions for Cloud Datastore.

source "https://rubygems.org"

gem "sinatra"
gem "google-cloud-datastore"

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 save command. Then, the ten most recent visits are retrieved in descending order using the Dataset run command.

require "digest/sha2"
require "sinatra"
require "google/cloud/datastore"

get "/" do
  # Save visit in Datastore
  visit = dataset.entity "Visit"
  visit["user_ip"]   = Digest::SHA256.hexdigest request.ip
  visit["timestamp"] = Time.now
  dataset.save visit

  # Query the last 10 visits from the Datastore
  datastore = Google::Cloud::Datastore.new
  query     = datastore.query("Visit").order("timestamp", :desc).limit(10)
  visits    = datastore.run query

  response.write "Last 10 visits:\n"

  visits.each do |visit|
    response.write "Time: #{visit['timestamp']} Addr: #{visit['user_ip']}\n"
  end

  content_type "text/plain"
  status 200
end

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 Ruby docs