Start a new topic
Answered

Random data query

Hello,

I have looked through your entire api library for ios but couldn't find a method to  get for example 10 random objects satisfying the query


Best Answer

Grisha:


I'm not understanding why you would need to get 10 random objects, but let's say for the sake of argument you were making a trivia game, where picking random questions would make sense:


You could achieve this by numbering your objects (adding a questionNumber field for example) and then generating random numbers in your program (between 1 and x where x is the number of questions you have) and querying on the new field that you made.


Alternatively, you could probably use 10 sorted by their _id, this won't be random each time you use it, but will be in random order as _id is not incrementing.


Thanks,


Hi Grisha, have you considered using the skip and limit query modifiers, along with the _count endpoint, to achieve this? Example (I'm using a collection, but the same applies to /user queries as well):

Send a request to /appdata/your-app-id/your-collection/_count, which returns the number of entities in that collection (say, 100).
Generate a random integer between 0 and 100.
Send a request to /appdata/your-app-id/your-collection/&limit=1&skip=your-random-integer.

This should be much more efficient than running a group operation. Does that work?

 


1 person likes this
Answer

Grisha:


I'm not understanding why you would need to get 10 random objects, but let's say for the sake of argument you were making a trivia game, where picking random questions would make sense:


You could achieve this by numbering your objects (adding a questionNumber field for example) and then generating random numbers in your program (between 1 and x where x is the number of questions you have) and querying on the new field that you made.


Alternatively, you could probably use 10 sorted by their _id, this won't be random each time you use it, but will be in random order as _id is not incrementing.


Thanks,


1 person likes this

I am making social network ,but your approach can work if I want to fetch 100 random objects satisfying query, I will group them with count function by user id , then get the raw array of all user_ids and generate random number in that range to pick id. 
Just one more question then, If I fetch using Grouping ( reduced function count) it doesn't load anything except specified fields right? ( Worrying about perfomance issue in case if there are a lot of users).