realm / realm-java

Realm is a mobile database: a replacement for SQLite & ORMs
http://realm.io
Apache License 2.0
11.45k stars 1.75k forks source link

Sort by RealmDictionary values #7817

Closed KunNiu closed 1 year ago

KunNiu commented 1 year ago

Problem

I created field RealmDictionary, and now I want to query all dates with a specified key, then sort by it's value. Now I query out all specified values, and then sort the list myself. Can I complete the steps in one query?

Solution

No response

Alternatives

No response

How important is this improvement for you?

I would like to have it but have a workaround

Feature would mainly be used with

Local Database only

KunNiu commented 1 year ago

More extras, if I sort the list by self, then I cannot use the change listener, because index changed.

rorbech commented 1 year ago

Hi @KunNiu. We are actually working on supporting this in our query engine in https://github.com/realm/realm-core/pull/5311. Unfortunately it hasn't been finalized yet, but once done you should be able to achieve this with an raw predicate like:

realm.where(Object::class).rawPredicate("ANY dictionaryField.@keys == 'KEY' SORT(dictionaryField['key'] DESC)").findAll()

Until that, I don't really see a way to listen for notifications and correlate with a result sorted by Kotlin/Java in one operation. There are options to query only objects with a given key in a dictionary field. You could maybe find a workaround where it is acceptable to just listen for the right updates and correlate with the sorted collection yourself by primary key or some other field.

val sortedObjects = realm.where(Object::class).rawPredicate("ANY dictionaryField.@keys == 'KEY'").findAll().sortedBy {
   it.dictionaryField['KEY']
}
KunNiu commented 1 year ago

@rorbech thanks for your reply, I'm glaid to hear that, and do you have plan that when this feaure will be included in new release version?

rorbech commented 1 year ago

@KunNiu We just released 10.16.0 that includes this new feature.