composite key in google cloud datastore

2019-08-07 16:20发布

问题:

In GCP Datastore & I've a kind with 3 properties.

  1. key (auto-generated)
  2. externalId
  3. externalName

I can't allow duplicate externalName + externalId combination. Is it possible to maintain this uniqueness?

回答1:

Options:

  1. Do what Robert said in his answer, although you would want to using the concatenation of externalId & externalName as the key. The only downside of this is if externalId or externalName change, 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.
  2. Check for Model.query(Model.externalId== externalId, Model.externalName == externalName).count(1) > 0 before 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.
  3. Save the unique combo in a key, but in a separate table called Unique. Here's an example from webapp2'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..