英文:
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)
参考资料:
我同意这个方法有些晦涩和文档不足。
英文:
You should use the magic constant __key__
to filter by keys:
Query(T).Filter("__key__ =", key)
References:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论