Created
April 10, 2019 04:50
-
-
Save notheotherben/e8915dd55abda6f67a81f1cfd5edb469 to your computer and use it in GitHub Desktop.
CosmosDB Random Document Stored Procedure
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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