如何按两个字段对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 Realtime数据库不支持对多个属性的查询,仅支持对单个子属性的查询.因此,您猜测需要创建一个额外的字段来保留这两个字段是正确的.因此,要实现此目的,您需要创建一个新字段,该字段在数据库中应如下所示:
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 Realtime数据库不同, 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屋!