Search code examples
python-3.xgoogle-cloud-datastore

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


I manage to make a connection to a Google Cloud Datastore databased. Now I want to get some entities given their Key/Id. Right now I am doing the following:

from google.cloud import datastore


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

I get "Invalid key: '325899977574122'". What could be the cause of error? That Id exist, a city does have that key/Id.


Solution

  • It looks like it needs to be of type google.cloud.datastore.key.Key

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

    Also, 325899977574122 is probably supposed to be cast to a long

    So something like this:

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

    EDIT:

    Also if youre trying to retrieve a single id, you should probably use this:

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

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

    Fetching by ID is faster than doing a query