2

In SharePoint 2013 restful api, is there a way to put in the url for user profiles, that you want say 5 random items from the target list? I don't want to download the whole thing and then take 5 random things from that.

Thanks

2
  • I'm not aware of any random function in OData, but one hack could be to fetch lowest and highest user ID, then pick 5 random IDs from that range (either with re-query for holes or fetching more than 5)?
    – eirikb
    Aug 22, 2015 at 9:45
  • Just did a quick test with Angular on 365, and the first ID was 4 and the last was 1073741823, so not such a good idea after all. But that might be special for System Account, so you could perhaps filter them out, set a filter with le 1000000000 or similar...
    – eirikb
    Aug 22, 2015 at 9:58

1 Answer 1

0

I am not aware of OData supporting any random like methods. I fear you need to do this in at least two http requests. For example:

  1. Fetch the Id of the users on the site. The filter ignores the system account.

    /_api/Web/SiteUserInfoList/Items?$select=Id&$filter=Id lt 1073741823
    
  2. Next step is to pick out random people.

    var items = d.results.items,
        numPeople = 5,
        peopleIds = [];
    
    // if we don't have enough people we simply select all the Ids available
    if (items.length < numPeople) {
        for (var i = 0; i < items.length; i++) {
            peopleIds.push(items[i].Id);
        }
    
    // otherwise we loop until we have the amount of people we want
    } else {
        while (peopleIds.length < numPeople) {
            var person = items[Math.floor(Math.random() * items.length)];
            // make sure the Id doesn't exist from before
            if (peopleIds.indexOf(person.Id) === -1) {
                peopleIds.push(person.Id);
            }
        }
    }
    
  3. Last step is to use the selected Ids to query the rest of the profile information we need.

    // using join and the Ids to build the filter
    '/_api/Web/SiteUserInfoList/Items?$filter=Id eq ' + peopleIds.join(' or Id eq ')
    

I realize this isn't ideal if you have thousands of users. But limiting the selected data to a minimum, then doing the randomization logic, then fetching the specific users we wish to know about might just do it.

I guess it will never happen, but in case there are no users, I'd add some sanity checks along the way, especially on the last step.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.