Google Cloud Datastore から key を使ってデータを取得する for Golang

NoSQL が初めてならば、Google Cloud Datastore について簡単に概要を掴んでおいたほうが良い。

Cloud Datastore Overview
https://cloud.google.com/appengine/docs/standard/go/datastore/

特に以下の項目は重要。

From: 'Comparison with traditional databases'

「Kind」「Entity」「Property」「Key」が何を意味しているのかは覚えておいたほうが良い。



さて、Key はリレーショナルデータベースで言うところの「主キー」に該当するが、
この主キーを使った検索をどうやるのか分からなかった。

intID を採用している場合、Entity の Key はこれになる。



一般的な Property に対するクエリは次のようなものになる。

q := datastore.NewQuery("Person").Filter("Height <=", maxHeight)


しかし、Key にはこの方法が使えなかった。


いろいろ調べているうちに、結局公式リファレンスの方の最初に書いてあったのを見つけた。


App Engine > Documentation > Go > Standard Environment
"Creating, Retrieving, Updating, and Deleting Entities"
https://cloud.google.com/appengine/docs/standard/go/datastore/creating-entities

の "Retrieving entities" にちゃんと書いてある。

To retrieve an entity identified by a given key, pass the *datastore.Key as an argument to the datastore.
Get function. You can generate the *datastore.Key using the datastore.NewKey function.

--
employeeKey := datastore.NewKey(ctx, "Employee", "asalieri", 0, nil)
addressKey := datastore.NewKey(ctx, "Address", "", 1, employeeKey)
var addr Address
err = datastore.Get(ctx, addressKey, &addr)

例えば、単純な構造の intID の Entity を取得したいならば次のようなコードになる

key := datastore.NewKey(ctx, "YourEntity", "", 5629499534213120, nil)
var yourEntity YourEntity
err := datastore.Get(ctx, key, &yourEntity)

これで 'yourEntity' に該当する Entity が入った。


こういうときは常に思うが、公式リファレンスを参照する癖をつけた方が良い...。