如何在Firebase中为条件选择排序字段查询创建索引?



例如,在Firestore中,我有这样的JSON

// Document 1
{
"type":"Child",
"createdDate":"01/01/2020",
"birthDate":"08/01/2002",
}
// Document 2
{
"type":"Adult",
"createdDate":"05/01/2020",
"birthDate":"08/01/1990",
}

我想把这个功能变成firebase查询

(a, b) {
DateTime da = a["type"] == "Child" ? a["createdDate"]: a["birthDate"];
DateTime db = a["type"] == "Child" ? a["createdDate"]: a["birthDate"];
return da.compareTo(db);
}
// In short if it a Child, select `createdDate` to compare, else select `birthDate` to compare.

我可以在firebase中这样做吗?

我不能查询所有数据然后在前端排序因为我想使用FirestoreListView

我看到的唯一方法是在DB中创建一个助手字段,该字段显示儿童的createdDate和成人的birthDate。然后您可以对这个字段

进行排序

我没有你的class模型,所以我在列表上运行逻辑,但是你也可以在模型上这样做。

首先你不能用两种不同的排序来排序列表,我建议首先将它们分成两组作为childadult,然后排序主题然后合并在一起,对于分组,我使用集合包,假设这是你的列表:

List<Map<String, String>> dataList = [
{
"type": "Child",
"createdDate": "08/01/2020",
"birthDate": "09/01/2002",
},
{
"type": "Child",
"createdDate": "01/01/2020",
"birthDate": "08/01/2002",
},
{
"type": "Adult",
"createdDate": "05/01/2020",
"birthDate": "10/01/1990",
},
{
"type": "Adult",
"createdDate": "05/01/2020",
"birthDate": "08/01/1990",
},
];

你可以这样排序:

var grouped = groupBy(dataList, (Map value) => value['type']);
var result = grouped.entries
.map((e) {
e.value.sort(
(a, b) => e.key == "Child"
? a["createdDate"]
.toString()
.compareTo(b["createdDate"].toString())
: a["birthDate"]
.toString()
.compareTo(b["birthDate"].toString()),
);
return e.value;
})
.toList()
.expand((element) => element)
.toList();

结果:

[
{type: Child, createdDate: 01/01/2020, birthDate: 08/01/2002},
{type: Child, createdDate: 08/01/2020, birthDate: 09/01/2002},
{type: Adult, createdDate: 05/01/2020, birthDate: 08/01/1990},
{type: Adult, createdDate: 05/01/2020, birthDate: 10/01/1990}
]