Swift 按Firebase中的指定子级进行筛选和排序
我正在使用Firebase和Swift构建一个游戏应用程序,并像这样存储我的数据Swift 按Firebase中的指定子级进行筛选和排序,swift,firebase,nested-queries,Swift,Firebase,Nested Queries,我正在使用Firebase和Swift构建一个游戏应用程序,并像这样存储我的数据 players: { "category": { "playerId": { name: "Joe", score: 3 } } } 根据分数,我需要提出两个问题: 从单个类别中获得前5名玩家 获得游戏的前100名玩家 我可以使用 ref.child("players").child(category).queryOrdered(
players: {
"category": {
"playerId": {
name: "Joe",
score: 3
}
}
}
根据分数,我需要提出两个问题:
- 从单个类别中获得前5名玩家李>
- 获得游戏的前100名玩家
ref.child("players").child(category).queryOrdered(byChild: "score").queryLimited(toLast:5)
但我很难理解第二个问题。如何有效地执行此操作?您需要添加额外的数据结构以允许第二个查询(这在NoSQL数据库中非常常见),或者更改当前结构以允许两个查询 后者可以通过将数据转换成一个单一的平面列表来实现,其中包含一些额外的合成属性。例如
players: {
"playerId": {
category: "category1"
name: "Joe",
score: 3,
category_score: "category1_3"
}
}
使用新的附加属性category
和category_score
,您可以获得具有以下属性的类别的最佳得分者:
ref.child("players")
.queryOrdered(byChild: "category_score")
.queryStarting(atValue:"category1_")
.queryEnding(atValue("category1_~")
.queryLimited(toLast:5)
总分前100名包括:
ref.child("players")
.queryOrdered(byChild: "score")
.queryLimited(toLast:100)
有关这方面的更多信息,请参见我的回答:Firebase数据库查询只能对单个属性进行排序/筛选。在许多情况下,可以将要筛选的值组合到单个(合成)特性中。有关此方法和其他方法的示例,请参见我的回答:。您需要添加额外的数据结构以允许第二次查询(这在NoSQL数据库中非常常见),或者更改当前结构以允许两次查询 后者可以通过将数据转换成一个单一的平面列表来实现,其中包含一些额外的合成属性。例如
players: {
"playerId": {
category: "category1"
name: "Joe",
score: 3,
category_score: "category1_3"
}
}
使用新的附加属性category
和category_score
,您可以获得具有以下属性的类别的最佳得分者:
ref.child("players")
.queryOrdered(byChild: "category_score")
.queryStarting(atValue:"category1_")
.queryEnding(atValue("category1_~")
.queryLimited(toLast:5)
总分前100名包括:
ref.child("players")
.queryOrdered(byChild: "score")
.queryLimited(toLast:100)
有关这方面的更多信息,请参见我的回答:Firebase数据库查询只能对单个属性进行排序/筛选。在许多情况下,可以将要筛选的值组合到单个(合成)特性中。有关此方法和其他方法的示例,请参见我的回答:。不确定是谁否决了此方法,因为这似乎是一个有效的问题。我投了反对票。你能接受改变数据库的结构吗?我想如果你改变结构会很容易,结构可以修改。不确定是谁否决了这个,因为这似乎是一个有效的问题。我反对。你能接受你改变数据库的结构吗?我认为如果你改变结构会很容易,结构可以被修改。