Stored Procedures and Triggers - CosmosDB Indexing and Querying
Syntax
Stored Procedures:
function <storedProcedureName>(<inputParam1>, <inputParam2>, ...) {
//stored procedure logic
}
Triggers:
function <triggerName>() {
var context = getContext();
var request = context.getRequest();
var documentToCreate = request.getBody();
//trigger logic
request.setBody(documentToCreate);
}
Example
Stored Procedure:
function addItem(item) {
var collection = getContext().getCollection();
var response = getContext().getResponse();
if (!item.id) {
throw new Error('Id property must be set');
}
collection.createDocument(collection.getSelfLink(), item, function (error) {
if (error) throw new Error('Error: ' + JSON.stringify(error));
response.setBody('Item added successfully');
});
}
Trigger:
function sampleTrigger() {
var context = getContext();
var request = context.getRequest();
var documentToCreate = request.getBody();
documentToCreate.timestamp = new Date().toISOString();
request.setBody(documentToCreate);
}
Explanation
Stored Procedures and Triggers are server-side code that can be executed on CosmosDB documents. A Stored Procedure is a function that can be called to perform a specific action on one or more documents. A Trigger, on the other hand, is executed automatically when a specific event occurs on a document, such as document insert, update, or delete.
Stored Procedures and Triggers are written in JavaScript and executed on the CosmosDB server. They can be used to implement custom business logic, data validation, and data manipulation. Stored Procedures and Triggers can be stored and managed in the CosmosDB database, making them easy to maintain and scale.
Use
Stored Procedures and Triggers can be used for a variety of tasks, such as:
- Data validation and verification
- Custom business rules and workflows
- Complex data manipulation and aggregation
- Real-time updates and notifications
- Cross-document consistency
Important Points
- Stored Procedures and Triggers are executed on the CosmosDB server, which means they can be more efficient and scalable than client-side code.
- Stored Procedures can accept input parameters and can perform complex operations on one or more documents.
- Triggers can be used to modify incoming documents and can be triggered on document insert, update, and delete events.
- Stored Procedures and Triggers can be managed and versioned in the CosmosDB database, ensuring that they are always up-to-date and consistent across all instances.
Summary
Stored Procedures and Triggers are powerful server-side code that can be used to implement custom business logic, data validation, and data manipulation on CosmosDB documents. They are written in JavaScript, executed on the server, and can be managed and versioned in the database. Stored Procedures and Triggers are an essential tool for building complex and scalable applications on CosmosDB.