4
votes

I'm experimenting with App Engine, Datastore and Objectify 4. I have a working Objectify query that fetches all entities of a given kind from the Datastore. I'm trying to sort the result based on a date:

List<MyEntity> entities = OfyService.ofy().load().type(MyEntity.class).order("-createdDate").list();

But after I add order, the query returns 0 records. This is my entity class:

@Entity
public class MyEntity
{   
    @Id Long id;
    Long userID;
    @Ignore String username;
    @Index String name;
    String url;
    String description;
    @Index Date createdDate;
    @Index int viewCount;
}

I've tried to order by other data types with no success. Why does this happen?

2
It's hard to say without seeing the full code, but do you get results if you remove the - in the order() to return results in ascending order? According to the documentation, App Engine should automatically create an index for Queries with no filters and only one sort order on a property, either ascending or descending.tx802
I get the same result when removing the "-" from order(). For some reason, none of the indexes defined in the entity class are stored in the datastore, please read the answer I just addedAndré

2 Answers

2
votes

We need to define index manually in WEB-INF/datastore-indexes.xml.

<?xml version="1.0" encoding="utf-8"?>
<datastore-indexes
  autoGenerate="true">
    <datastore-index kind="AppMedia" ancestor="false">
        <property name="createdDate" direction="desc" />
    </datastore-index>
</datastore-indexes>

Then the index is created properly and the query will work. Note : The query will only work with those rows added after the index is configured properly.

0
votes

I looked in the datastore through cloud.google.com and when opening any entity, all the fields were marked as "Not indexed", including the fields that are defined with @Index in my entity class. When I manually marked the fields "Indexed" in the datastore, the query with sort worked. Shouldn't all fields that are marked with @Index in the entity be indexed in the datastore when saved through Objectify? What am I missing here?