【问题标题】:Unable to retrieve entity from datastore created using IncompleteKey()无法从使用 IncompleteKey() 创建的数据存储中检索实体
【发布时间】:2019-10-04 18:33:53
【问题描述】:

我正在使用“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 方法检查是否存在,而不是如果键为 nil,我想调用 datastore.Put 来添加新实体。但是,在每种情况下(即使对于 Datastore 中已经存在的实体),“keys”变量总是得到 nil 值。

keys, err := s.DataLayer.GetAll(ctx, query, &tExp)

因此,在数据存储中使用相同的键值创建了多个实体。我无法找出如何在 golang 中解决此问题。

注意:- 数据存储中的实体具有结构

["Datastore 在调用 IncompleteKey 方法时自动生成的名称/ID", Key, Value].

【问题讨论】:

    标签: go google-cloud-datastore


    【解决方案1】:

    首先,如果你想获取一个特定的实体,你应该使用Get而不是GetAll,因为Get是强一致的,而GetAll不是。

    其次,由于您使用不完整的密钥执行 Put,因此您将永远不会在仅添加到 Datastore 的新实体上发生冲突。您似乎想使用 transaction 来获取和放置具有完整密钥的实体,该完整密钥已传递到您的函数中。

    【讨论】:

    • 嗨@JimMorrison,首先我想检查是否存在任何具有相同键值(不是数据存储的ID)的实体,如果不是,我想创建具有给定键的新实体和value 字段的值,其 ID 应为数字形式并由数据存储本身生成,以便在更新时可以跟踪此 ID。
    • 从结构字段中删除 noindex 后我的问题解决了
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多