简体   繁体   中英

Why not filter by part of entity key?

I have an objectify entity defined like this:

public class MyEntity1
{
    @Id @Indexed String             phoneNumber;
    @Parent @Indexed Key<MyEntity2> parentEntityKey;
}

When I try to filter by phoneNumber, I get the following error message:

Cannot (yet) filter by @Id fields on entities which have @Parent fields.

The reason for this construction is that I want to be able to get (instead of querying) those records when I know both phoneNumber and parentEntityKey, which I sometimes do. In some other cases, I only know the phoneNumber and wish to query for it.

Is this a shortcoming of Objectify or Datastore and can I find a work-around? Do you have a proposal which solves my two requirements (get instead of query when I know both values and query by phoneNumber when only that is known)?

This is the nature of datastore keys.

You cannot filter by the id part of a key. You can filter by an entire key, or you can use an ancestor() query to "filter" by the key hierarchy, but you cannot filter by just the @Id part of a key. Think about how keys are laid out in BigTable:

/parentkind1/parentid1/parentkind2/parentid2/kind/id

You can't do a range scan on just the id part.

It sounds like what you want to do is create an indexed phoneNumber property on your entity, separate from the @Id field. Yes it's duplicate data but you need the separate index no matter what, so the extra data serialized into the blob is fairly negligible.

Note that you can't query on indexed properties inside of a transaction, and queries will have eventual consistency behavior. If you require phone numbers to be assigned uniquely, you will need to create a separate PhoneNumber entity without a @Parent whose @Id is the phone number itself. XG transactions let you create this uniqueness entity and associate it with your MyEntity1 in a single consistent operation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM