I'm using FirebaseRecyclerAdapter and pass FirebaseRecyclerOptions with some query into constructor. Each item has number of fields including timestamp a and another integer field b. So I want items with older a but less b to be on top of list. It's easy to implement with sqlite, but not so easy with nosql. It seems I need to add some extra field which keeps both fields: String.valueOf(a) + String.valueOf(b) but how to achieve asc / desc properties?

Loading the whole list and sorting in Java is not an option.

Solution 1

Unfortunately, Firebase Realtime database does not support queries on multiple properties, supports only queries on a single child property. So, you're correct in guessing that you'll need to create an extra field to keep both fields. So to achieve this, you need to create a new field which in your database should look like this:

   --- itemId
          --- a: valueOfA
          --- b: valueOfB
          --- a_b: valueOfA_valueOfB

So as you see, the a_b property combines the values that you want to filter on.

Unlike Firebase Realtime database, Cloud Firestore allows compound queries. You should take a look at this. So a query as the one below is allowed in Cloud Firestore without creating a combined property.

itemIdRef.whereEqualTo("a", "valueOfA").whereEqualTo("b", "valueOfB");

When you order strings this is the normal ordering method. A quick fix would be to add two zeros before each second element like this: "1516428687_001", "1516428687_002", "1516428687_012". Now your order will be fine. For more explanations, please see my answer from this post.