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.
Just like embedded classes, Objectify converts
Map<String, String>
to the low-levelEmbeddedEntity
object, which is not indexible. However, if you @Index yourMap
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:If you are just looking for key existence, try
filter("hashMapfieldName.key !=", null)
.I am not sure what
Objectify
does forHashMap
.But as per the docs,
HashMap
is not a supported field type inDatastore
. Even if weserialize
it and store, it will be stored as Blob which is by defaultunindexded
.So to my knowledge,
HashMap
cannot be queried as there is no indexes created for it.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:
@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 queryingofy().load().type(MyEntity.class).filter("values", value)