Google云数据存储区只存储唯一的实体 [英] Google cloud datastore only store unique entity

本文介绍了Google云数据存储区只存储唯一的实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图用Google Datastore学习NoSQL,但我遇到了一个唯一性问题。



考虑一个电子商务商店,它有类别和产品。 p>

您不希望数据库中存在两个具有相同SKU的产品。

因此,我使用JSON插入一个实体:

  {sku:1234,product_name:Test product} 

它显示了两个字段。但后来我可以再次做到这一点,我有两个或更多相同的产品。



你如何避免这种情况?你可以让sku字段是唯一的吗?

在插入前我需要做一个查询吗?



问题出现在类别中。我应该只使用一个实体来处理我的所有类别,并将其构建到我的JSON中?



这里有一个很好的惯例吗?

解决方案

创建一种名为'sku'的新类型。当您创建新产品时,您需要对产品实体和sku实体进行事务性插入。



例如,假设您想添加一个名称 product 的新产品,其ID为 abc




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



为确保属性sku的唯一性,您总是要插入一个实体名称为 sku的实体和等于属性值的id:




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



上面的示例实体有一个属性对于创建日期 - 只是可选的我作为示例的一部分投入。



现在,只要插入这两个部分作为在同一笔交易中,您将确保sku属性具有唯一的价值。这是因为:




  • 插入确保写入将失败,如果该号码的sku实体已存在

  • 交易确保编写产品实体(使用sku值)并且sku实体是原子的 - 所以如果sku不是唯一的,那么编写sku实体将失败,导致产品实体写入也失败。


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.

You do not want two products of the same SKU in the database.

So I insert an entity with JSON:

{"sku": 1234, "product_name": "Test product"}

And it shows up with two fields. But then I can do that again and I have two or more identical products.

How do you avoid this? Can you make the sku field unique?

Do I need to do a query before insert?

The same issue arises with categories. Should I just use one entity for ALL my categories and stucture it in my JSON?

What is a good common practice here?

解决方案

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.

这篇关于Google云数据存储区只存储唯一的实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆