I'm exploring appengine (java), and as per subject, how do I, using DatastoreService, get an Entity based on开发者_开发知识库 Key and conditions?
In my scenario, Trainer's have many to many relationship with User's, so I have my structure as so
Trainer(id, name, type, department)
User(id, name, address, is_activated)
TrainerUser(id, trainer_id, user_id)
Now to get all User under a particular Trainer, I'd fetch all the user_id from TrainerUser filtering by trainer_id. All's ok. Then I want to get all activated User under the Trainer, so my plan is to loop over the fetched user_id's and call something like
Query q = new Entity('User');
q.addFilter('Key', EQUAL, userId);
q.addFilter('is_activated', EQUAL, True);
But as far as I know, Key is not a real physical property in which you can access using addFilter(), so the code at the top will just return me an empty Entity.
Is there a way to reference Key in the Entity? Any magic keyword for that?
Entity.KEY_RESERVED_PROPERTY
is the property name you can use for keys.
A reserved property name used to refer to the key of the entity. This string can be used for filtering and sorting by the entity key itself.
so to filter by key
query.addFilter(Entity.KEY_RESERVED_PROPERTY, FilterOperator.EQUAL, myKey);
Why not filter by trainer and is_activated? Here is Python-like pseudocode:
activated_users_for_trainer = User.all().filter("trainer =", trainer_key).filter("is_actived =", True).fetch(100)
Its more easy and optimal I think get the entity by id and then if exists verify if is_activated, to the datastore is faster and cheaper get by ID an entity the next verifications runs just on memory. As in this responses
精彩评论