Skip to content

Instantly share code, notes, and snippets.

@notheotherben
Created April 10, 2019 04:50
Show Gist options
  • Save notheotherben/e8915dd55abda6f67a81f1cfd5edb469 to your computer and use it in GitHub Desktop.
Save notheotherben/e8915dd55abda6f67a81f1cfd5edb469 to your computer and use it in GitHub Desktop.
CosmosDB Random Document Stored Procedure
function getRandomDocument(filterQuery){
var collection = getContext().getCollection();
var result = null;
var count = 0;
var pageSize = 50;
function query(responseOptions) {
return (filterQuery && filterQuery.length) ?
collection.queryDocuments(collection.getSelfLink(), filterQuery, responseOptions, onReadDocuments) :
collection.readDocuments(collection.getSelfLink(), responseOptions, onReadDocuments);
}
function getRandomInt(max) {
return Math.floor(Math.random() * max);
}
function onReadDocuments(err, docFeed, responseOptions) {
if (err) throw err
if (docFeed)
docFeed.forEach(function (doc) {
if (getRandomInt(count++) === 0) {
result = doc;
}
});
if (!responseOptions.continuation || !query(responseOptions)) {
getContext().getResponse().setBody(result);
}
}
if (!query({ pageSize: pageSize }))
throw new Error("The query was not accepted by the server");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment