问题
In GCP Datastore & I've a kind with 3 properties.
- key (auto-generated)
- externalId
- externalName
I can't allow duplicate externalName + externalId combination. Is it possible to maintain this uniqueness?
回答1:
Options:
- Do what Robert said in his answer, although you would want to using the concatenation of
externalId&externalNameas the key. The only downside of this is ifexternalIdorexternalNamechange, then you wouldn't be able to change your key. You'd have to delete the current object and make a new one; which could have cascading impacts on any other object with key properties that point to this object. - Check for
Model.query(Model.externalId== externalId, Model.externalName == externalName).count(1) > 0before you save. Downside here is that fetching a key is strongly consistent, but queries are eventually consistent. This means if 2 threads submitting the same pair at the same time would both succeed. - Save the unique combo in a key, but in a separate table called
Unique. Here's an example fromwebapp2's source code where they did just that. https://github.com/GoogleCloudPlatform/webapp2/blob/master/webapp2_extras/appengine/auth/models.py#L33
回答2:
Datastore doesn't enforce constraints like this. In this case the closest you can get is yo use 'externalId' as the key.
回答3:
Use externalId + <some delimiter> + externalName as the key.
Eg : externalId:externalName, externalId|externalName etc..
来源:https://stackoverflow.com/questions/51303734/composite-key-in-google-cloud-datastore