google-app-engine - google app engine go datastore 使用 key 检查实体是否存在

标签 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 检索完整的实体?

最佳答案

要仅检索键,请将 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)

关于google-app-engine - google app engine go datastore 使用 key 检查实体是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34985161/

相关文章:

time - 使用 time.Format 时的本地化

python - 如何在 Python3 中使用 App Engine 安排 Cloud Datastore 导出

java - 应用引擎 : Copy live Datastore to local Dev Datastore

api - Google App Engine 删除 Post Put 操作

java - 如何在没有 web.xml 的情况下将 App Engine 项目更新到 Java 11?

python - golang 和 python 节俭通信

json - 戈朗 : quickly access data of maps within maps

google-app-engine - 如何在 Google App Engine 数据存储中创建引用列表?

google-app-engine - locationId "europe-west"代表比利时还是欧盟的多区域?

google-app-engine - 为什么 Google Cloud Tasks 这么慢?