在Firebase实时数据库中获取随机条目 [英] Get random entries in firebase real-time database

查看:105
本文介绍了在Firebase实时数据库中获取随机条目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的代码,用于从实时数据库中获取5个项目:

This is my code to get 5 items from realtime database:

val database = FirebaseDatabase.getInstance()
val brandReference = database.getReference("brandGame").limitToFirst(5)
brandReference.addValueEventListener(object : ValueEventListener {
    override fun onDataChange(dataSnapshot: DataSnapshot) {
         dataSnapshot.children.forEach {
            ...
         }
    }
}

这是我的实时数据库的样子:

And this is how my real-time database looks like:

随机获得5件物品的最佳方法是什么?我知道实时数据库中还没有随机函数.

What's the best way to get 5 items randomly? I know there isn't a random function in real time database yet.

推荐答案

如果知道brandGame/-引用中元素的数量,则可以选择1和numberOfElements之间的5个随机数并进行检索.这将导致对数据库的多次调用.

If you know the number of elements in the brandGame/-reference, you could pick 5 random numbers between 1 and numberOfElements and retrieve those. This would result in multiple calls to the database.

或者,您可以从brandGame/-参考下载所有内容,并使用纯Kotlin随机选择5个元素.但是然后您必须下载参考中的所有内容,这可能会很多.

Alternatively, you could download everything from the brandGame/-reference and just pick 5 random elements using pure Kotlin. But then you must download everything in the reference, which could be a lot.

最好的选择是设置一个执行选择5个随机选项"-逻辑服务器端的云功能. https://firebase.google.com/docs/functions/但这要求您写一些js :)

The best option is to set up a cloud function that does the "pick 5 random options"-logic server side. https://firebase.google.com/docs/functions/ But this requires that you write some js :)

正如您所说,没有内置的方法可以从引用中获取随机元素.

As you say, there is no built-in way to get random elements from a reference.

这篇关于在Firebase实时数据库中获取随机条目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆