Can I run a Cosmos DB Query in the code itself? All I could do right now is run a query before the code runs (input). What I need is to first run some code and then grab data in cosmos DB. How do I do this using javascript?
2 Answers
When using the Input Binding, there is an option (but only for C#) to pull in the DocumentClient, which you can use to run any query or operation.
If your constraint is running on JavaScript, you can certainly use the Cosmos DB JS SDK directly within your Function instead of using the Input Binding like so:
const cosmos = require('@azure/cosmos');
const endpoint = process.env.COSMOS_API_URL;
const masterKey = process.env.COSMOS_API_KEY;
const { CosmosClient } = cosmos;
const client = new CosmosClient({ endpoint, auth: { masterKey } });
// All function invocations also reference the same database and container.
const container = client.database("MyDatabaseName").container("MyContainerName");
module.exports = async function (context) {
const querySpec = {
query: "SELECT * FROM Families f WHERE f.lastName = @lastName",
parameters: [
{
name: "@lastName",
value: "Andersen"
}
]
};
const { result: results } = await container.items.query(querySpec).toArray();
context.log(results);
}
COSMOS_API_URL and COSMOS_API_KEY should be environment variables pointing to the Azure Cosmos account endpoint and Master Key. You can replace the names of the database and container and tinker with the query as needed.
Comments
You could refer to the example code in this link:
function.json:
{
"bindings": [
{
"name": "query",
"type": "httpTrigger",
"direction": "in"
},
{
"name": "$return",
"type": "http",
"direction": "out"
},
{
"type": "documentDB",
"name": "documents",
"databaseName": "<your-database-name>",
"collectionName": "<your-collection-name>",
"sqlQuery": "SELECT * FROM d WHERE d.name = {Name} and d.city = {City}",
"connection": "<connectionstring-setting-name>",
"direction": "in"
}
],
"disabled": false
}
function code:
module.exports = function (context, req) {
var documents = context.bindings.documents;
var totalDocuments = documents.length;
context.log('Found '+ totalDocuments +' documents');
if(totalDocuments === 0){
context.res = {
status: 404,
body : "No documents found"
};
}
else {
context.res = {
body: documents
};
}
context.done();
};
Please note: above code works for the Azure Function V1 binding configuration.
