当前位置: > > > > 无法从使用 IncompleteKey() 创建的数据存储中检索实体
来源:stackoverflow
2024-04-25 16:06:31
0浏览
收藏
亲爱的编程学习爱好者,如果你点开了这篇文章,说明你对《无法从使用 IncompleteKey() 创建的数据存储中检索实体》很感兴趣。本篇文章就来给大家详细解析一下,主要介绍一下,希望所有认真读完的童鞋们,都有实质性的提高。
问题内容
我正在使用“cloud.google.com/go/datastore”从数据存储区存储、更新和检索实体。我创建的结构是 –
type texp struct { key string `json:"key" datastore:"key,noindex"` value string `json:"value" datastore:"value,noindex"` } type service struct { datalayer *datastore.client }
当我使用 datastore.incompletekey(“texp”, nil) 为此创建 id 时,我能够创建实体并可以在真实数据存储中看到它。
func (s service)addtexp(ctx context.context, request interface{}) (interface{}, error) { req := request.(*texp) var texp []texp var texp2 texp texp2.key = req.key texp2.value = req.value query := datastore.newquery("texp").filter("key =", req.key).namespace("adlive") keys, err := s.datalayer.getall(ctx, query, &texp) if err != nil { log.errorf(ctx,"error occurred while checking existence of key in kind") } if keys == nil { log.infof(ctx,"keys: %v ", keys) k := datastore.incompletekey("texp", nil) k.namespace = "adlive" k.kind = "texp" if _, err := s.datalayer.put(ctx, k, &texp2); err != nil { return nil, marvin.newjsonstatusresponse( "could not add texp in ds", http.statusbadrequest, )} } return "ok",nil }
问题是在创建任何实体之前,我想确保该数据存储中不存在任何具有相同键值的实体。为此,首先我尝试使用 getall 方法检查是否存在,如果键为零,我想调用 datastore.put 来添加新实体。然而,在每种情况下(即使对于数据存储中已经存在的实体),“keys”变量总是获得零值。
keys, err := s.DataLayer.GetAll(ctx, query, &tExp)
因此,在数据存储中使用相同的键值创建多个实体。我无法找出如何在 golang 中解决此问题。
注意:- 在数据存储实体中具有结构
[“数据存储区在调用 incompletekey 方法时自动生成的名称/id”,key,value]。
解决方案
首先,如果要获取特定实体,应该使用 而不是 GetAll,因为 Get 是强一致的,而 GetAll 不是。
其次,由于您正在使用不完整的密钥执行 Put,因此您将永远不会与仅添加到数据存储中的新实体发生冲突。看来您希望使用 来获取和放置具有传递到函数中的完整密钥的实体。
今天关于《无法从使用 IncompleteKey() 创建的数据存储中检索实体》的内容介绍就到此结束,如果有什么疑问或者建议,可以在公众号下多多回复交流;文中若有不正之处,也希望回复留言以告知!