google app engine go datastore check for entity existence using key

huangapple go评论61阅读模式
英文:

google app engine go datastore check for entity existence using key

问题

给定一个实体的字符串ID键,我如何检查数据存储中是否存在相应的实体。我不想完全获取实体,我只想检查实体是否存在。

如果我获取完整的实体来检查其存在性,是否会影响性能?或者是否有更好的方法?

var Person struct {
   stringId string //用于生成键的字符串ID
   //其他许多属性。
}

//插入到数据存储
_, err := datastore.Put(ctx, datastore.NewKey(ctx, entityKind, stringId, 0, nil), entity)
//检索实体
datastore.Get(ctx, datastore.NewKey(ctx, entityKind, stringId, 0, nil), entity);

除了为给定的字符串ID检索完整的实体之外,是否有更好的方法来检查实体是否存在?

英文:

Given a stringId key for an entity, how do I check if there is a corresponding entity in datastore. I do not want to fetch the entity completely. I want to check if the entity exists or not.<br>
Is there a performance impact if I fetch the complete entity to check its existence? Or is there a better way?
<!-- language: go -->

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);

<br>
Instead of retrieving complete entity for a given stringId, is there a better way to check the entity exists?

答案1

得分: 3

要仅检索键(key),请在查询的末尾添加 KeysOnly(),例如:

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

是的,仅键查询应该更快,引用自文档

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

另外,要通过键检索实体,您还可以使用特殊属性 __key__,例如:

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

To retrieve only key(s) add KeysOnly() to the end of your query, ie

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

And yes, keys only query should be faster, quote from the 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

BTW, to retrieve an entity by it's key, you can also use the special property __key__, ie

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

huangapple
  • 本文由 发表于 2016年1月25日 12:34:07
  • 转载请务必保留本文链接:https://go.coder-hub.com/34985161.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定