Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to get 5 random rows from a model #431

Closed
bvallelunga opened this issue Jan 20, 2014 · 8 comments
Closed

How to get 5 random rows from a model #431

bvallelunga opened this issue Jan 20, 2014 · 8 comments

Comments

@bvallelunga
Copy link

I have a users model and I want to be able to get 5 random rows. @spartan563 do you have any suggestions on how to do this?

@dxg
Copy link
Collaborator

dxg commented Jan 20, 2014

There was some discussion here and here.

There is a chainable orderSql statement which accepts raw SQL. One could combine it with limit().
It's not a performant solution, but there is more discussion on the internets.

@bvallelunga
Copy link
Author

after doing some research I was able to use this

models.users.all().limit(5).orderRaw("rand()").run

@bvallelunga
Copy link
Author

im closing this issue, thanks again for your help.

@notheotherben
Copy link
Collaborator

As dxg said, your solution works but is horrible on performance as it first sorts all rows in the db using random nunbers and only then selects elements. If your database server is close then you are probably better off using skip+limit and making multiple queries - will vastly reduce your database server load

@bvallelunga
Copy link
Author

@spartan563 could you give me an example of how to do the skip + limit?

@bvallelunga bvallelunga reopened this Jan 20, 2014
@notheotherben
Copy link
Collaborator

I believe the idea is to do a count(), and then use native Math.random() * count as your skip, and then depending on how random something needs to be you can either set limit as the number of elements you require or limit: 1 and n queries to retrieve the records you need.

Some pseudocode (sync design, would need to make it async for Node)

var count = db.model.count(...);
var models = [];
while(models.length < n)
    models.push(db.model.find().skip(Math.random() * count).limit(1));

@dresende
Copy link
Owner

orm-random - adds Model.getRandom and Model.findRandom using the technique @spartan563 described

@bvallelunga
Copy link
Author

thank you @dresende

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants