1
votes

I'm working through some documentation for the google cloud datastore API

Namely https://googleapis.github.io/google-cloud-python/latest/datastore/client.html and https://googleapis.github.io/google-cloud-python/latest/_modules/google/cloud/datastore/entity.html#Entity

Using both sources I've created the following. I'm extremely confused by client.key(), namely the 1234 and namespace. My datastore shows the keys which seems to be a random? unique number and I have not seen any reference to a namespace. Why is this code sample specifying an integer and a namespace? Is there a better way to generate a key or can these two parameters be safely omitted?

    from google.cloud import datastore
    client = datastore.Client()
    key = client.key('Collection', 1234, namespace='_Doctest')
    entity = datastore.Entity(key=key)
    entity['property'] = 'value'
    client.put(entity)

key description

1

1 Answers

1
votes

I usually create keys directly without the namespace, just using the Entity kind and let datastore do the rest (you could specify an ID as well, but it's optional) this way you are creating an entity with a partial key (specifying only the kind) and once you put the entity in the datastore, the entity key is updated with an ID, to be a complete key (now has kind and ID)

key = client.key('Collection') # create partial key <Key('Collection')>
entity = datastore.Entity(key=key) # create entity using the partial key
entity['property'] = 'value'
client.put(entity)

# Print the full key <Key('Collection', 5293786145123) project=project-id>
print(f"Entity key = {entity.key}") 

Note: you can also create a key with parent (Entity Group) by adding the parent key to the new entity key assignment in the first line

key = client.key('Collection', parent=<parent_key>)