1

I am working on a project using the gcloud cli tools. I am using Python + Flask for developing the application. My main reference points have been the Google Datastore documentation as well this How-to tutorial guide.

I have some entities in my Datastore and these entities have some properties. Entities are created in the application, with the Key set to the default Key (a.k.a incomplete key).

I am able to access the entities alright. And using projection, I can also access the properties of each entity. However, is there a way to only extract the Key from an entity? Example:

>>> print(list(user_query.fetch()))
[<Entity('User', 5097358505279488) {...}>]

This works alright when I want to access the properties. However, I cannot access the key 509... I have also tried:

>>> for user in user_query.fetch():
       print(user.key)
       ...
>>> <Key('User', 5097358505279488), project=...>

While it returns the whole Key object, I couldn't find a way to extract only the key. I have scoured the documentation for a solution, but it hasn't returned anything so. I am wondering if this is even possible at this point.

davidism
  • 121,510
  • 29
  • 395
  • 339
Saneyar
  • 63
  • 9
  • The docs imply that [Keys](https://cloud.google.com/datastore/docs/concepts/entities#key) are JSON objects. Can you access the individual keyValue element using the [typical method of working with JSON objects in Python](https://stackoverflow.com/questions/12788217/how-to-extract-a-single-value-from-json-response)? – Frodnar Apr 03 '21 at 07:36
  • @Frodnar That does not work unfortunately :( It throws the following error: `TypeError: Object of type Key is not JSON serializable`. I don't think the Key is stored in a way like the rest of the properties are. – Saneyar Apr 03 '21 at 09:47
  • Hate to send you down another rabbit hole when clearly I don't understand this issue myself, but could it be stored as a [protocol buffer](https://developers.google.com/protocol-buffers)...? – Frodnar Apr 03 '21 at 10:13
  • @Frodnar I don't think that is possible as the Datastore API does not allow that. But I appreciate the help none the less. – Saneyar Apr 04 '21 at 00:26

3 Answers3

2

You use this to get id

print(user.key.id)
Sammrafi
  • 399
  • 4
  • 8
1

It sounds like you are trying to get a projection of key.id. Unfortunately, this is not possible. You can do a keys-only query that returns the keys, then you can use a list comprehension to get the data you want, e.g. [key.id_or_name for key in key_only_query.fetch_page()]

Jim Morrison
  • 2,784
  • 1
  • 7
  • 11
  • While the solution isn't exactly as you outlined, I was eventually able to come up with the solution I needed. Thank you very much for your help. – Saneyar Apr 04 '21 at 13:14
1

You can call the .id property on a datastore entity to get the key as an integer value.

for user in user_query.fetch():

print(user.id)

julianhatwell
  • 1,074
  • 1
  • 8
  • 17