Search code examples
androidrealmjdbcrealm

Realm fetch 10 object which has the max value in their group


At this moment i migrate from ORMLite database to Realm database.
I was able to to translate most of the queries without any problems but in this one case I have no idea how it should look like. Any suggestions?

I got Realm object with field:

EpisodeId as Integer
serieId as Integer
„watchedDate” as Date

now i want to query last 10 watched serieId. In SQL it should like it (semantic may be wrong):

  Select *, max(watched_date) as 'maxdate' from watched_entity group by serieId  order by 'maxdate' LIMIT 10

Solution

  • Realm does not, for the time being, support LIMIT, and for a good reason since RealmResults are not a copy of your data, which means there is not a huge memory penalty in carrying such reference. Just iterate over your RealmResults and pick the first 10 elements manually.

    Another note about your model. Keep in mind that Realm is not a relational database, and it uses links instead to specify the relationships among objects. A more sound approach in Realm would be something like (pseudo-code):

    class Serie extends RealmObject
     - String name
     - etc...
    
    class Episode extends RealmObject
     - Serie serie
     - boolean watched
     - Date lastWatched
     - etc...
    

    This makes queries easier to write.

    Also, still regarding your specific query, we currently still lack the support for GROUPBY so you would have to resolve the series manually, but we're thinking of ways to allow this in the future.