我正在尝试创建玩家匹配算法。所以基本上我希望它能像那样工作:
算法:
- 玩家创建指定
bet
和gameType
的游戏请求。 - 服务器从这个列表中订阅以下一些查询:
{
'gameRequests': {
'1': {
createdAt: 1454777718074,
uid: 123,
bet: 10,
gameType: 'nhl'
},
'2': {
createdAt: 1454777718075,
uid: 123,
bet: 20,
gameType: 'nhl'
},
'3': {
createdAt: 1454777718076,
uid: 321,
bet: 10,
gameType: 'nhl'
},
}
}
我会收到带有键 '1'
、'3'
的请求。
- 现在我只需删除键为
'1'
、'3'
的 child 并为他们创建一个游戏。
我有什么:
到目前为止,我是通过加载整个 gameRequests
分支来完成的。
randomGamesRef.on('value', onGameRequestsUpdate)
function onGameRequestsUpdate (snapshot) {
const gameRequests = snapshot.val()
const pairs = _.chain(gameRequests)
// Transform to array
.values()
// Group by sport and bet size
.groupBy((req) => req.gameType + '+' + req.bet)
// Map groups to pairs
.map((group) => {
return _.chain(group)
.uniqBy('createdBy')
.take(2)
.value()
})
.filter((pairs) => pairs.length === 2)
.value()
// Now having this pairs I can delete them
// from the database and create new game
}
但是每次都将所有内容加载到内存中似乎不是一个好主意。
问题:您将如何在 Firebase 中实现它?
最佳答案
在 NoSQL 中,您通常最终会按照您希望在代码中访问数据的方式对数据进行建模。因此,与其读取所有游戏请求,然后按 gameType
对它们进行分组,不如将它们分组。和 bet
在代码中,考虑将它们存储在结合了 gameType
的键下和 bet
:
{
'gameRequests': {
'nhl_10': {
'1': {
createdAt: 1454777718074,
uid: 123,
},
'3': {
createdAt: 1454777718076,
uid: 321,
}
},
'nhl_20': {
'2': {
createdAt: 1454777718075,
uid: 123,
}
}
}
}
现在你的代码变成了:
function onGameRequestsUpdate (snapshot) {
snapshot.forEach(function(gametypeSnapshot) {
if (gametypeSnapshot.numChildren() >= 2) {
// there is at least one request pair for this game type
}
});
};
我一直推荐人们阅读 this article , 因为它解释了 NoSQL Data Modeling techniques比如这个。
关于algorithm - Firebase游戏匹配算法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35243870/