Val*_*hyn 2 c# .net-core azure-functions azure-cosmosdb
是否可以从azure函数(例如时间触发器)运行Cosmos DB存储过程(在azure门户中创建的sp)。
我需要的是通过时间触发器来查询集合中的文档(输入绑定),修改其中的某些字段并进行更新(如DocumentClient.UpsertDocumentAsync),然后将更新后的文档存储回集合中。
第1步:请在您的cosmos数据库中创建存储过程。
样本存储过程js代码:
function sample() {
var collection = getContext().getCollection();
var isAccepted = collection.queryDocuments(
collection.getSelfLink(),
'SELECT * FROM root r where r.id = "1"',
function (err, feed, options) {
if (err) throw err;
if (!feed || !feed.length) {
var response = getContext().getResponse();
response.setBody('no docs found');
}
else {
var a = new Date();
var doc = feed[0];
doc.time = a;
collection.replaceDocument(doc._self,doc,function(err) {
if (err) throw err;
});
var response = getContext().getResponse();
response.setBody(JSON.stringify("update success"));
}
});
if (!isAccepted) throw new Error('The query was not accepted by the server.');
}
Run Code Online (Sandbox Code Playgroud)
步骤2:创建c#天蓝色函数TimeTrigger。
示例功能代码:
using System;
using Microsoft.Azure.Documents.Client;
public static void Run(TimerInfo myTimer, TraceWriter log)
{
private static DocumentClient client;
static string endpoint = "https://***.documents.azure.com:443/";
static string key = "***";
client = new DocumentClient(new Uri(endpoint), key);
StoredProcedureResponse<bool> sprocResponse = await client.ExecuteStoredProcedureAsync<bool>(
"/dbs/db/colls/coll/sprocs/updatetest/");
if (sprocResponse.Response) log.Info(sprocResponse.Response);
log.Info($"Cosmos DB is updated at: {DateTime.Now}");
}
Run Code Online (Sandbox Code Playgroud)
步骤3:在azure-functions中添加引用的文档数据库程序集。
您可以单击Azure函数>“查看文件”>添加一个名为'project.json'(如果不存在)的新文件。在此文件中编写以下代码,然后单击“运行”以安装程序包:
{
"frameworks": {
"net46":{
"dependencies": {
"Microsoft.Azure.DocumentDB": "1.20.1"
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
更多详细信息,您可以参考此文档。
希望对您有帮助。
| 归档时间: |
|
| 查看次数: |
2167 次 |
| 最近记录: |