Hide
Google Cloud Datastore

Getting started with Google Cloud Datastore and Ruby/JSON

This page discusses how you can get started with Google Cloud Datastore using Ruby. Follow the steps in Sign Up to make sure you are ready to run this example. After activation, you will have a <dataset-id> (same identifier as your Google Cloud Project ID) that you need to run the code.

Step 1: Set up your environment

In this step we'll show you how to create a Google Compute Engine (GCE) instance where you can run this example. If you already have an environment where you can run the code, go to Step 2.

When you set up a GCE instance, make sure it has the scopes datastore and userinfo-email so that you can access Google Cloud Datastore. For example, you can use the following gcloud compute command to create an instance:

$ INSTANCE_NAME=<instance-name>
$ gcloud compute instances create $INSTANCE_NAME --scopes datastore userinfo-email

When the instance is ready, log into the instance (for example, using gcloud compute ssh) and install Ruby with rubygems and rvm.

$ sudo apt-get update
$ sudo apt-get install ruby
$ curl -sSL https://get.rvm.io | bash -s stable

In order to make API calls to the Datastore, you need to install the google-api-client gem:

$ rvm use 2
$ gem install google-api-client

Step 2: Get service account credentials

You need to configure a <service-account> and the <path-to-private-key-file> for the demo code to work. Ruby support for Compute Engine service accounts is not yet implemented).

Run the following commands (in a bash-like shell):

# configure your credentials
export DATASTORE_SERVICE_ACCOUNT=<service-account>
export DATASTORE_PRIVATE_KEY_FILE=<path-to-private-key-file>

You can get the service account credentials from the Google Developers Console.

Step 3: Review the demo code file

The code for the demo is in a file called adams.rb file. The comments in the sample's source explain its behavior in detail:

adams.rb

Step 4: Run the code

Download and unzip the latest version of the google-cloud-datastore samples:

$ unzip google-cloud-datastore-1beta2-rev1-2.1.1.zip

Run the adams.rb demo with your <dataset-id> as a parameter. It will prompt for the question and validate your answer.

$ ruby google-cloud-datastore-1beta2-rev1-2.1.1/ruby/demos/trivial/adams.rb <dataset-id>
Meaning of life?
> 11
Don't Panic!

With this example, you learned how to use the:

  • google-api-client gem to connect to the Datastore API.
  • begin_transaction method to start a transaction.
  • lookup method to retrieve entities by key from your dataset.
  • commit method to send mutations to entities in your dataset and commit the transaction.

Now, you are ready to learn more about the Key Datastore Concepts and look at the JSON API reference.