Google cloud datastore only store unique entity

前端 未结 3 1912
伪装坚强ぢ
伪装坚强ぢ 2021-01-20 04:29

I am trying to learn NoSQL with Google Datastore but I am running into a problem with uniqueness.

Consider an ecommerce store, it has categories and products.

<
3条回答
  •  野趣味
    野趣味 (楼主)
    2021-01-20 04:34

    Create a new kind called 'sku'. When you create a new product, you'll want to do a transactional insert of both the product entity and the sku entity.

    For example, let's say you want to add a new product with the kind name product with the id of abc:

    • "product/abc" = {"sku": 1234, "product_name": "Test product"}

    To ensure uniqueness on the property "sku", you'll always want to insert an entity with the kind name sku and the id that equals the property's value:

    • "sku/1234" = {"created": "2017-05-11"}

    The above example entity has a property for created date - just something optional I threw in as part of the example.

    Now, as long as you insert both of these as part of the same transaction, you will be ensuring that the "sku" property has a unique value. This works because:

    • Insert ensures write will fail if the sku entity for that number already exists
    • The transaction ensures writing the product entity (with the sku value) and the sku entity are atomic - so if the sku isn't unique, writing the sku entity will fail, causing the product entity write to also fail.

提交回复
热议问题