suman j
suman j

Reputation: 6980

google app engine go datastore check for entity existence using key

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.
Is there a performance impact if I fetch the complete entity to check its existence? Or is there a better way?

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


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

Upvotes: 1

Views: 1774

Answers (1)

ain
ain

Reputation: 22759

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("__key__ =", qKey)

Upvotes: 3

Related Questions