mercredi 23 mars 2016

Randomly get one row from 10.000 results with Parse SDK

I know that Parse didn't implement the random feature and I have read many articles about selecting a random row with Parse but I couldn't find a good solution for my case.

I would like to get a random user who was connected in the last 5 days in my app. Here is how I wanted to proceed (with Swift) :

// Calculate the last 5 days
let today = NSDate()
let lastWeek = NSCalendar.currentCalendar().dateByAddingUnit(.Day,
                                                              value: -5,
                                                              toDate: today,
                                                              options: NSCalendarOptions(rawValue: 0))

// Find only the users who were logged in the last 5 days
let findReceiverQuery = PFQuery(className: "_User")
findReceiverQuery.whereKey("updatedAt", greaterThan: lastWeek!)
findReceiverQuery.findObjectsInBackgroundWithBlock({ (users, receiverError) in
    if(receiverError == nil) {

        let nbUsers = UInt32(users!.count)

        if(nbUsers > 0) {

            let random_number = Int(arc4random_uniform(nbUsers) + 0)
            print(users![random_number])

        }
    }
})

This is working well but what happens if I have more than 10.000 results since Parse is limiting the number of rows returned to 1.000. Can I fix that with by using a random value on skip too ?

Thanks!




Aucun commentaire:

Enregistrer un commentaire