How to randomly pull 25 records from a table?

e_wilber
Tera Guru

I'm working on a flow that sets the Description field on the RITM record where I need to pull 25 random assets from alm_asset (the display name).


I know how to query the table and get results, but how do I randomly pull in 25 records so I can built a list?

7 REPLIES 7

Chaitanya ILCR
Kilo Patron

Hi @e_wilber 

try this

var randomNumber;
var numberOfRecords = 25;

var almGr = new GlideAggregate('alm_asset');
almGr.addAggregate('COUNT');
almGr.query();
if (almGr.next())
    randomNumber = Math.round(Math.random(25) * (almGr.getAggregate('COUNT') - numberOfRecords));
var now_GR = new GlideRecord('alm_asset');
now_GR.chooseWindow(randomNumber, randomNumber+numberOfRecords);
now_GR.query();
while (now_GR.next()) {
    gs.info(now_GR.getDisplayValue());
}

Please mark my answer as helpful/correct if it resolves your query.

Regards,
Chaitanya

 

Robert H
Mega Sage

Hello @e_wilber ,

 

Here is a quick and straight forward method:

 

var names = [], randomNames = [],
	gr = new GlideRecord('alm_asset');
gr.query();
while (gr.next()) {
	names.push(gr.getValue('display_name'));
}
for (var i = 0; i < 25; i++) {
	randomNames.push(names[Math.floor(Math.random() * names.length)]);
}
gs.info('Here are 25 random assets: ' + randomNames.join('\n'));

 

Regards,

Robert 

KevinWhite
Tera Contributor

The lookupRandomSample function below will pull a return a random list of sysIDs from a GlideRecord query. It calculates the total population size of the query, randomly picks records from that population, and then uses the GlideRecord#setLocation method to select the specific records. The benefit of setLocation is that your are choosing specific records instead of reading every row in the table to populate a local array. The downside to this approach is that setLocation is not available in the scoped GlideRecord, only global. The function also ensure that the results are unique and can be applied to any GlideRecord query.

var gr = new GlideRecord('alm_asset');
gr.query();

if (gr.next()) {
	var ids = lookupRandomSample(gr, 25);
	gs.info(ids);
}

function lookupRandomSample(population, sampleSize) {
	if (!sampleSize) {
		return [];
	}
	var populationSize = population.getRowCount();
	if (sampleSize > populationSize) {
		gs.warn('Sample size cannot be larger than the population size');
		return [];
	}
	var recordIds = [];
	var selectedIndices = {};
	for (var i = 0; i < sampleSize; i++) {
		var randomIndex = Math.floor(Math.random() * populationSize);
		while (selectedIndices[randomIndex]) {
			randomIndex = Math.floor(Math.random() * populationSize);
		}
		selectedIndices[randomIndex] = true;
		population.setLocation(randomIndex);
		recordIds.push(population.sys_id.toString());
	}
	return recordIds;
}