0

I have the following code

var vec:ViewEntryCollection = database.getView("view").getAllEntriesByKey("Mykey",true)

how can I make "vec" in random order using SSJS (or java) so that I get a new order every time?

Thomas Adrian
  • 3,543
  • 6
  • 32
  • 62
  • How big is the collection? – shillem Jul 04 '17 at 07:14
  • well, not sure, it could be big but that is not likely, probably under 200 entries. If it makes it easier it would be enough to not return the whole collection. just need to return maybe 10 entries in random order – Thomas Adrian Jul 04 '17 at 07:22
  • 2
    If you only need to return a small fraction of all entries, then I don't recommend shuffling/reordering the whole collection. You could simply use `vec.getNthEntry(Math.floor(Math.random()*vec.getCount()));` in a loop to get the amount of random entries you want to return. if you want to prevent returning duplicate entries you would of course have to keep track of entries already taken (for example by saving the taken entries in a simple SSJS object with the index as key). – xpages-noob Jul 04 '17 at 09:08
  • May I ask what use case this has? – Sven Hasselbach Jul 04 '17 at 11:25
  • yes you may :-) the entries are photos that I need to display randomly – Thomas Adrian Jul 04 '17 at 15:14

3 Answers3

2

How about having a secondary sort column on the view with a formula of @Unique. Would need to refresh the view each time and performance may not be great if the view is big.

Rob Mason
  • 1,385
  • 10
  • 23
2

Considered the average collection size I would loop through the collection and add each item to a Java list or a JavaScript array.

If you go Java you can use Collections.shuffle.

If you go JavaScript you can use well established functions/algorithms

shillem
  • 1,260
  • 7
  • 12
1

For better performance, do NOT keep collection entries in memory. First, make list/array of UNIDs from your view. That will be the slowest part. Then pick any random number and pick desired number of UNIDs from the list/array. Call getDocumentByUnid or initialize (say 10) datasources.

Frantisek Kossuth
  • 3,524
  • 2
  • 23
  • 42