GAE w/ Objectify - Can you query a HashMap?

2020-07-22 10:01发布

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.

3条回答
爷的心禁止访问
2楼-- · 2020-07-22 10:26

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).

查看更多
戒情不戒烟
3楼-- · 2020-07-22 10:38

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.

查看更多
smile是对你的礼貌
4楼-- · 2020-07-22 10:48

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)
查看更多
登录 后发表回答