如何按两个字段对 Firebase 记录进行排序 (Android) [英] How to sort Firebase records by two fields (Android)
问题描述
我正在使用 FirebaseRecyclerAdapter
并将带有一些查询的 FirebaseRecyclerOptions
传递给构造函数.每个项目都有多个字段,包括时间戳 a
和另一个整数字段 b
.所以我希望具有较旧 a
但较少 b
的项目位于列表顶部.用sqlite很容易实现,但用nosql就没有那么容易了.看来我需要添加一些额外的字段来保留两个字段:String.valueOf(a) + String.valueOf(b)
但是如何实现 asc/desc 属性呢?
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?
加载整个列表并在 Java 中排序不是一种选择.
Loading the whole list and sorting in Java is not an option.
推荐答案
遗憾的是,Firebase 实时数据库不支持对多个属性的查询,仅支持对单个子属性的查询.因此,您正确地猜测您需要创建一个额外的字段来保留这两个字段.因此,要实现这一点,您需要在数据库中创建一个新字段,该字段应如下所示:
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:
Firebase-root
|
--- itemId
|
--- a: valueOfA
|
--- b: valueOfB
|
--- a_b: valueOfA_valueOfB
如您所见,a_b
属性组合了您要过滤的值.
So as you see, the a_b
property combines the values that you want to filter on.
与 Firebase 实时数据库不同,Cloud Firestore 允许 复合查询.你应该看看这个.因此,Cloud Firestore 中允许使用以下查询,而无需创建组合属性.
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");
当您对字符串进行排序时,这是正常的排序方法.一个快速的解决方法是在每个第二个元素之前添加两个零,如下所示:"1516428687_001"
, "1516428687_002"
, "1516428687_012"
.现在你的订单会很好.有关更多解释,请参阅我的回答 发布.
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.
这篇关于如何按两个字段对 Firebase 记录进行排序 (Android)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!