google App Engine go datastore 使用密钥检查实体是否存在
google app engine go datastore check for entity existence using key
给定一个实体的 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 检索完整的实体?
要仅检索键,请将 KeysOnly()
添加到查询的末尾,即
q := datastore.NewQuery(entityKind).Filter(...).KeysOnly()
是的,仅键查询应该更快,引用自 doc:
A keys-only query returns just the keys of the result entities instead of the entities themselves, at lower latency and cost than retrieving entire entities
顺便说一句,要通过它的键检索实体,您还可以使用特殊的 属性 __key__
,即
qKey := datastore.NewKey(ctx, entityKind, stringId, 0, nil)
q := datastore.NewQuery(entityKind).Filter("__key__ =", qKey)
给定一个实体的 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 检索完整的实体?
要仅检索键,请将 KeysOnly()
添加到查询的末尾,即
q := datastore.NewQuery(entityKind).Filter(...).KeysOnly()
是的,仅键查询应该更快,引用自 doc:
A keys-only query returns just the keys of the result entities instead of the entities themselves, at lower latency and cost than retrieving entire entities
顺便说一句,要通过它的键检索实体,您还可以使用特殊的 属性 __key__
,即
qKey := datastore.NewKey(ctx, entityKind, stringId, 0, nil)
q := datastore.NewQuery(entityKind).Filter("__key__ =", qKey)