2
votes

Using the Google Cloud Datastore, I want to list my entities. I want to retrieve them ordered by the value of a property depending of its name.

Java class model:

public class ContainerEntity {
    @Index
    String id;
    @Index
    private List<NameValueProperty> properties;
}

public class NameValueProperty {
    @Index
    private String name;
    @Index
    private String value;
}

Data set example:

"items": [
{
   "id": "114191058616700893306-20180416-120212-125-Qotx9AlsSRHg4cJhya",
   "properties": [
    {
     "name": "propertyIWantToOrderBy",
     "value": "BBBB"
    },
    {
     "name": "propertyIDoNotCareTheOrder",
     "value": "1522540800000"
    }
   ]
  },
  {
   "id": "114191058616700893306-20180416-120718-199-Qotx9AlsSRHg4cJhya",
   "properties": [
    {
     "name": "propertyIWantToOrderBy",
     "value": "AAAA"
    },
    {
     "name": "propertyIDoNotCareTheOrder",
     "value": "1522540800000"
    }
   ]
  }
}

How can I do that using objectify? I tried using this snippet of code but it does not work:

Query<ContainerEntity> query = ObjectifyService.ofy().load().type(ContainerEntity.class);
query = query.filter("properties.name = ", "propertyIWantToOrderBy")
             .order("properties.value");

First it filters (which I don't want), and then it looks like it's not correctly order on the property with the name "propertyIWantToOrderBy". Is there any solution/workaround to do that? Would like to do something like order("properties.value where properties.name='propertyIWantToOrderBy'"). The main point of this design is to have a dynamic entity.

Objectify version: 5.1.22 Jdk: 8

1

1 Answers

2
votes

List properties can be confusing when you try to filter and order them. Try this approach instead:

public class ContainerEntity {
    @Id
    String id;
    @Index
    private Map<String, String> properties = new HashMap<>();
}

Now your query looks like this:

ofy().load().type(ContainerEntity.class).order("properties.propertyIWantToOrderBy");

BTW you don't @Index ids, which are not stored as regular properties. They need the @Id annotation.