Is there a clear way to query a table to get N random entries from that table after applying a filter?
The idea would be to have a list of questions in a table, with a category property for each question, and to query that table to get N random questions from a specific topic.
Any help or info would be much appreciated!
Thanks in advance!
I’d just generate the random number in your app and then add it as a query argument for the first parameter. That will return the first: n records within any filter or plain list.
Example:
query($filter: QuestionListFilter, $first: Int) {
questionsList(filter: $filter, first: $first) {
items {
any
fields
you
want
}
}
}
Thanks for your reply!
My question though was not really on how to get a random amount of questions but rather on a fixed amount of random questions. Meaning, for example, that I would like to fetch 5 questions at random which would all be different at every call.
So there is a simple approach here and a more complex approach as well. The simple approach would be something as follows. Write a random number generator that returns a number in the following range:
n >= 0 && n <= (records.length - # of questions wanted)
So, something like this:
function getRandomInt(max, slice) {
var n = Math.floor(Math.random() * Math.floor(max)) - slice;
return n < 0 ? 0 : n;
}
This way, when running the query you are able to specify the number of records you want using the first argument along with a random skip position of all filtered results. We’re pretty much-using pagination through querying a random page of results.
var numberOfRecordsInTable = 1000
var numberOfRecordsForFirstArg = 5
var skip = getRandomInt(numberOfRecordsInTable, numberOfRecordsForFirstArg)
var query = gql`query($skip: Int, $first: Int) {
questionsList(first: $first, skip: $skip) {
items { text }
}
}`;
Does this make sense?
For the more complicated approach, I think we’d have to make a custom View that generates a random number field. That field would then change on every query, and if sorted, reshuffle the results randomly each time.
You could do it with two GraphQL calls: query to fetch all question IDs, in your app randomly select some subset of these, and then make another query to fetch the relevant questions (some combination of filters or aliasing should work here).
Thank you all for the clear response!
I had a similar intuition at first but was not sure whether this was just a hacky solution or an actual solution to use for production.
I will get started on it then👌
Because this approach requires two consecutive requests, I was also wondering on the impact on the quotas as I have asked here: Calls to Table from Custom Resolver