问题
In GAE, when using Objectify, can you query a HashMap? If so how would would you write it?
ofy().load().type(MyClass.class).filter("hashMapfieldName", "keyQueryinggFor").list();
Does not seem to work where the hashMapfieldName
is a HashMap<String, String>
. I am looking to find entities where hashMapfieldName
contains a certain key.
回答1:
Just like embedded classes, Objectify converts Map<String, String>
to the low-level EmbeddedEntity
object, which is not indexible. However, if you @Index your Map
field (or embedded class field), Objectify will create a synthetic index that lets you query anyways.
Following your example, let's say you have a Map field named hashMapfieldName
containing the mapping of strings "key"
to "value"
. This query syntax will return entities that have the pair:
ofy().load().type(MyClass.class).filter("hashMapfieldName.key", "value");
If you are just looking for key existence, try filter("hashMapfieldName.key !=", null)
.
回答2:
I have a similar case where I have stored device specific values in an embedded hashmap where the device id is the key, and I need to query for all entities that contain a certain value.
The suggested solution by stickfigure above does work in my test environment. But I realized I cannot use it the real application since it will not scale to the number of users we are projecting. This is because Objectify will generate a property index for each hashmap key that I save. In my case, that means that every user's device will have its own index, which could be 100000 indexes!
So instead, I went for this alternative approach:
- in the
@OnSave
method on the entity I store the values that I want to search for in a separate indexed list, that I only use for querying - then I will do my filtered query like this:
ofy().load().type(MyEntity.class).filter("values", value)
回答3:
I am not sure what Objectify
does for HashMap
.
But as per the docs, HashMap
is not a supported field type in Datastore
. Even if we serialize
it and store, it will be stored as Blob which is by default unindexded
.
So to my knowledge, HashMap
cannot be queried as there is no indexes created for it.
来源:https://stackoverflow.com/questions/25437341/gae-w-objectify-can-you-query-a-hashmap