如何从 Python 3 对 Google 数据存储执行基于键的查询?

How to perform Key based queries to Google Datastore from Python 3?

我设法连接到 Google 云数据存储数据库。现在我想得到一些实体,给定它们的 Key/Id。现在我正在做以下事情:

from google.cloud import datastore


client = datastore.Client()
query = client.query(kind='City')
query.key_filter("325899977574122") -> Exception here

我得到 "Invalid key: '325899977574122'"。 错误的原因可能是什么?我存在,一个城市确实有那个key/Id。

看起来需要是google.cloud.datastore.key.Key

类型

https://googleapis.dev/python/datastore/latest/queries.html#google.cloud.datastore.query.Query.key_filter

此外,325899977574122 可能应该转换为 long

所以像这样:

client = datastore.Client()
query = client.query(kind='City')
query.key_filter(Key('City', 325899977574122L, project=project)) 

编辑:

此外,如果您要检索单个 ID,您可能应该使用这个:

https://googleapis.dev/python/datastore/latest/client.html#google.cloud.datastore.client.Client.get

client = datastore.Client()
client.get(Key('City', 325899977574122L, project=project)) 

通过 ID 获取比查询更快