2
votes

I would like to use an user entered string as the unique Key for an Entity. Suppose an user enters a key that is already in the datastore, I would like to return an error. Since the golang datastore API only has Put which also doubles as Insert, what is the best way to enforce uniqueness constraint?

Currently I'm trying to do…

Query(T).Filter("Key =", key)

…where key is constructed from the user entered value to test the existence of a duplicate, but 2 identical keys seem to return false with the equality (=) operator in the filter but true when calling Equal on the result.

How do I query by Key?

2

2 Answers

1
votes

You should use the magic constant __key__ to filter by keys:

Query(T).Filter("__key__ =", key)

References:

Java API constant values

Python documentation

I agree that this is somewhat obscure and under-documented.

1
votes

A query by key is called a "get": https://developers.google.com/appengine/docs/go/datastore/entities#Go_Retrieving_an_entity

There's almost no point in doing a query and filtering by key equality.