I’m learning Azure functions and have faced a problem.
The function hangs when getting a record from cosmos db.
I use the cosmos db emulator.
The function works properly without code that fetches records from cosmos db. I see log: First id value is: 3
.
const { app } = require('@azure/functions');
app.http('httpTrigger', {
methods: ['GET', 'POST'],
handler: async (request, context) => {
try {
const Id = request.query.get('id');
context.log(`First id value is: ${Id}`);
return {body: `Response id =${Id}`};
} catch (error) {
context.log(`Error: ${error}`);
return { status: 500, body: 'Internal Server Error' };
}
}
});
local.settings.json
{
"IsEncrypted": false,
"Values": {
"FUNCTIONS_WORKER_RUNTIME": "node",
"AzureWebJobsFeatureFlags": "EnableWorkerIndexing",
"AzureWebJobsStorage": "UseDevelopmentStorage=true",
"CosmosDBConnectionString":"AccountEndpoint=https://localhost:8081/;AccountKey=C2y6yDjf5/R+ob0N8A7Cgv30VRDJIWEHLM+4QDU5DE2nQ9nDuVTqobD4b8mGGyPMbIZnqyMsEcaGQy67XIw/Jw=="
}
}
But the function doesn’t work properly with the code that fetches records from cosmos db. I don’t see logs. It looks like the function was triggered but the code (logs) inside the handler was not executed.
const { app, input } = require('@azure/functions');
const cosmosInput = input.cosmosDB({
databaseName: 'my-database',
containerName: 'my-container',
connection: 'CosmosDBConnectionString',
sqlQuery: 'SELECT * FROM c'
});
app.http('httpTrigger', {
methods: ['GET', 'POST'],
authLevel: 'anonymous',
extraInputs: [cosmosInput],
handler: async (request, context) => {
try {
const Id = request.query.get('id');
context.log(`First id value is: ${Id}`);
const toDoItem = context.extraInputs.get(cosmosInput);
context.log(`Second id value is: ${Id}`);
return {body: `Response id =${Id}`};
} catch (error) {
context.log(`Error: ${error}`);
return { status: 500, body: 'Internal Server Error' };
}
}
});
I try to get records from cosmos db in an Azure function.
2
Answers
Try with the below code to retrieve data from Azure Cosmos DB Emulator using JavaScript functions v4.
Output:
First, start by verifying the Azure Functions logs, the query might be failing with authentication or connectivity issues. When working with the Emulator, there might be authentication issues (like missing certificates) that would make the Input binding fail in the background.
Secondly,
SELECT * FROM c
you are reading the entire Container every time you execute the Function, there is no filtering.This is a cross-partition query that can the more data the Container has, the longer the Function will take and the more RUs which increases the changes of throttling.
The intent of the Function is unclear, maybe the query should be filtered by the input? Like
SELECT * FROM c WHERE c.id = '{id}'
?