Developer Forum »
Aql Random order
58 posts

Came over this problem today. I was needing to get a given number of contents out of a Aql Query in a random order. Like with Linq to Objects: list.OrderBy(x=> Guid.NewGuid()).Take(20). is this possible to achieve? It is important that the ordering is done in the database and not in the code, so I don't end up getting all 1000 rows, ordering them and selecting the desired number of items.

181 posts

Hi!

We don't have any ways to do this using a database query today. But if you know the amount of data won't grow wildly past 1000, I would suggest you load the ids to a collection in memory on application start, and then use a function that randomly selects ids from that collection, and then using a Aql.In query to fetch the random nodes. Something like this:

 List<int> ids = GetProjectIds();        
        Random random = new Random();
        List<int> idsToFetchForThisRequest = new List<int>();
        for (int i; i < NumElements; i++) {
            idsToFetchForThisRequest.Add(ids[random.Next(0, ids.Count)]);        }
        List<ArticleBase> articles = WAFContext.Session.Query<ArticleBase>().Where(Aql.In(AqlArticleBase.NodeId,idsToFetchForThisRequest)).Execute();
58 posts

Well, I am sort of doing this already, but relying on the Webnodes cache heavily. It is a bit more complicated since there are over 100.000 items available, and they need to be filtered on one or more parameters which can lead to expensive querying. I'll just leave it as is for now. Thanks for the quick answer though! :)

1