Objectbox-java: Getting A random record from database

Created on 28 Jan 2017  路  5Comments  路  Source: objectbox/objectbox-java

more info required not sure about this

Most helpful comment

The use case can be done efficiently using LazyList in upcoming the 0.9.7: LazyList does not load all entities, but you have the result size so you can pick a random number smaller than the result size and get the entity. Makes sense?

All 5 comments

What is this about? Why would you want to get an random record?

In some cases, I can imagine, that one wants to show a random user / image out of a pool. Or imagine a learning card system, where one wants to show a random next question.

This can be solved, by simply getting a larger dataset with _getAll_ or a query with some filters and then selecting a random item from the returned subset. This is not efficient tho, when working on >10k items/rows. It would be really simply to just have a random() filter on a query object. Alternatively one you make this the default, for _findFirst_ or provide a similar function somewhat like _findRandom_.

I think it would make more sense to have a limit / topN / offset command, so that one could get a limited subset and do a random function on the resulting list with standard Java random APIs.

You could give every item an number from 1 to n and then generate a random integer between 1 and n.

@FabianTerhorst how about deleted IDs? You would need to look that query and make sure you really get an item... not as trivial I would claim.

The use case can be done efficiently using LazyList in upcoming the 0.9.7: LazyList does not load all entities, but you have the result size so you can pick a random number smaller than the result size and get the entity. Makes sense?

Was this page helpful?
0 / 5 - 0 ratings