gpt4 book ai didi

duplicates - 如何防止 Google Cloud Datastore 中出现重复值?

转载 作者:行者123 更新时间:2023-12-04 10:37:14 24 4
gpt4 key购买 nike

是否有任何机制可以防止我的实体的某些字段中出现重复数据?类似于 SQL unique 的东西。

否则,人们通常使用什么技术来防止重复值?

最佳答案

在 SQL 中对 UNIQUE 约束执行等效操作的唯一方法不会在像 Cloud Datastore 这样的 NoSQL 存储系统中很好地扩展。这主要是因为它需要在每次写入之前进行读取,以及围绕这两个操作的事务。

如果这不是问题(即,您不经常写入值),该过程可能类似于:

  1. 开始一个可序列化的事务
  2. 在所有 Kind 中查询属性 = 值的匹配项
  3. 如果查询匹配,则中止交易
  4. 如果没有匹配项,则插入属性为 value 的新实体
  5. 提交交易

使用 gcloud-python ,这可能看起来像...

from gcloud import datastore
client = datastore.Client()

with client.transaction(serializable=True) as t:
q = client.query(kind='MyKind')
q.add_filter('property', '=', 'value')

if q.fetch(limit=1):
t.rollback()
else:
entity = datastore.Entity(datastore.Key('MyKind'))
entity.property = 'value'
t.put(entity)
t.commit()

注意:Transaction 上的serializable 标志在 gcloud-python 中相对较新。参见 https://github.com/GoogleCloudPlatform/gcloud-python/pull/1205/files了解详情。


做到这一点的“正确方法”是设计你的数据,使关键是你对“独特性”的衡量,但在不了解你正在尝试做什么的情况下,我不能说太多。

关于duplicates - 如何防止 Google Cloud Datastore 中出现重复值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32078471/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com