Get random firebase database entry

2019-09-10 07:37发布

I've got users like this inside my database:

users
--45jklj4kljfejlk34 // random uid
----id: 1 // I add this manually when creating a user (maybe it helps getting a random user)
----someData: true
--454jkljkljefnd4lk
----id: 2
----someData: true

I want to get a random user, but I don't know how. I tried sth. like this:

let usersCount = DataService.sharedInstance.DB_USER_COUNT
let rand = Double(arc4random_uniform(UInt32(usersCount))) + 1
let userRef = DataService.sharedInstance.DB_REF_USERS.queryOrdered(byChild: "id").queryStarting(atValue: rand).queryLimited(toFirst: 1))

I get usersCount from the database. There, I increment the figure every time I add a user.

But this doesn't work. This is what I get if I printed this:

(/users {
    i = id;
    l = 1;
    sp = 1;
    vf = l;
})

Any suggestions, how I can achieve this?

1条回答
唯我独甜
2楼-- · 2019-09-10 08:22

So, as firebase works quite differently than relational based databases, redundancies seem acceptable in order to be fast and efficient. So I came up with a workaround that works for me.

When I create a user I add him to the "users" tree. Additionally, I add him to a "numUsers" tree (I'm terrible at choosing names, sorry for that). This looks like that:

users
--45jklj4kljfejlk34 // random uid
----id: 1
----someData: true
--454jkljkljefnd4lk
----id: 2
----someData: true

numUsers
--1: 45jklj4kljfejlk34
--2: 454jkljkljefnd4lk

So, "numUsers" consists of an id as key and the uid as value. Every time I add a new user, I grab the "usersCount" (which I incremented by 1 before) and use it as key.

This way, I can easily grab a random user by using this:

DataService.sharedInstance.DB_REF_USERS.child("\(rand)").observeSingleEvent(of: .value, with: {(snapshot) in print(snapshot) })
查看更多
登录 后发表回答