谷歌应用引擎使用密钥

时间:2016-01-25 04:34:07

标签: google-app-engine go google-cloud-datastore

给定实体的stringId键,如何检查数据存储区中是否存在相应的实体。我不想完全获取实体。我想检查实体是否存在。
如果我获取完整的实体以检查其存在,是否会对性能产生影响?或者,还有更好的方法?

var Person struct {
   stringId string //string id which makes the key
   //many other properties.
}

//insert into datastore
_, err := datastore.Put(ctx, datastore.NewKey(ctx, entityKind, stringId, 0, nil), entity)
//retrieve the entity
datastore.Get(ctx, datastore.NewKey(ctx, entityKind, stringId, 0, nil), entity);


而不是检索给定stringId的完整实体,是否有更好的方法来检查实体是否存在?

1 个答案:

答案 0 :(得分:3)

要仅检索密钥,请在查询末尾添加KeysOnly(),即

q := datastore.NewQuery(entityKind).Filter(...).KeysOnly()

是的,只有密钥查询应该更快,引用doc

  

仅键检查只返回结果实体的键而不是实体本身,比检索整个实体的延迟和成本更低

顺便说一句,要通过它的密钥检索实体,您还可以使用特殊属性__key__,即

qKey := datastore.NewKey(ctx, entityKind, stringId, 0, nil)
q := datastore.NewQuery(entityKind).Filter("__key__ =", qKey)