Google Cloud Datastore unique autogenerated ids

2019-07-25 00:28发布

问题:

I'm using Google Cloud Datastore and using namespaces to partition data. Some kinds are using autogenerated IDs from Cloud Datastore by creating keys like this:

var key = Datastore.key([
    'example'
]);

This code will generate a key with kind 'example' and Cloud Datastore automatically assign the entity an integer numeric ID. (Source: https://cloud.google.com/datastore/docs/concepts/entities#kinds_and_identifiers)

But this "unique" ID is only unique for its namespace. I have seen the same ID in different namespaces.

So my question is, is it possible to tell Cloud Datastore that autogenerated IDs must be unique for all the namespaces?

Maybe this question has not sense, but I would prefer to have unique IDs in all the datastore (if possible).

I have seen "allocateIds" function in Cloud Datastore documentation, but I would like to know if this function take care about namespaces or not, because I've seen I can include them in the request and I'm afraid the IDs are the same than the ones autogenerated by Cloud Datastore.

Thank you in advance!

回答1:

No: You can not tell Datastore to allocate unique IDs across all entity groups and namespaces.

However there is an easy fix: if you believe in statistics and correctly seeded random number generators you be generally better off if you generate your own GUIDs for keys.

If you don't believe in statistics and random numbers you can still generate a GUID and transactionally verify that it doesn't exist in your Datastore before writing the entity in question.

If you are truly desperate to have Datastore do id allocation for you it is possible to make a call AllocateIds manually and ask it to allocate an id for a constant key. (For example, ask it to allocate for an arbitrary (but unchanging) key in the default namespace, and it will return you an integer which will be unique to use somewhere else).