What is the best way (performance wise) to enforce key uniqueness in Appengine datastore with golang?

huangapple go评论98阅读模式
英文:

What is the best way (performance wise) to enforce key uniqueness in Appengine datastore with golang?

问题

我想使用用户输入的字符串作为实体的唯一键。假设用户输入的键已经存在于数据存储中,我想返回一个错误。由于golang数据存储API只有Put方法,它同时充当插入操作,那么如何最好地强制执行唯一性约束?

目前我正在尝试使用以下代码...

Query(T).Filter("Key =", key)

...其中key是由用户输入的值构建的,用于测试重复项的存在,但是两个相同的键在过滤器中使用等号(=)操作符时似乎返回false,但在调用结果的Equal方法时返回true。

如何通过键进行查询?

英文:

I would like to use an user entered string as the unique Key for an Entity. Suppose an user enters a key that is already in the datastore, I would like to return an error. Since the golang datastore API only has Put which also doubles as Insert, what is the best way to enforce uniqueness constraint?

Currently I'm trying to do…

Query(T).Filter("Key =", key)

…where key is constructed from the user entered value to test the existence of a duplicate, but 2 identical keys seem to return false with the equality (=) operator in the filter but true when calling Equal on the result.

How do I query by Key?

答案1

得分: 1

你应该使用魔术常量__key__按键进行过滤:

Query(T).Filter("__key__ =", key)

参考资料:

Java API常量值

Python文档

我同意这个方法有些晦涩和文档不足。

英文:

You should use the magic constant __key__ to filter by keys:

Query(T).Filter("__key__ =", key)

References:

Java API constant values

Python documentation

I agree that this is somewhat obscure and under-documented.

答案2

得分: 1

按键查询被称为“获取”:https://developers.google.com/appengine/docs/go/datastore/entities#Go_Retrieving_an_entity

几乎没有必要进行查询并通过键相等进行过滤。

英文:

A query by key is called a "get": https://developers.google.com/appengine/docs/go/datastore/entities#Go_Retrieving_an_entity

There's almost no point in doing a query and filtering by key equality.

huangapple
  • 本文由 发表于 2014年1月6日 06:22:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/20939981.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定