如何使用Azure功能更新集合

时间:2017-12-07 10:45:32

标签: azure azure-cosmosdb azure-functions

我想创建绑定到cosmos DB的azure函数。

  • 每当在“A”集合中发生某些插入时,我想更新“B”集合。
  • “B”集合具有在集合“A”中插入后要调用的存储过程。

我是Azure和cosmos-DB的新手。

建议我完成这项要求需要做些什么。

到目前为止,我已经创建了Azure功能 enter image description here

还使用以下代码更新了function.json。

{
  "bindings": [
    {
      "type": "cosmosDBTrigger",
      "name": "input",
      "direction": "in",
      "leaseCollectionName": "leases",
      "connectionStringSetting": "cdb-swm-dev-001_DOCUMENTDB",
      "databaseName": "admin",
      "collectionName": "aomsorders",
      "createLeaseCollectionIfNotExists": true
    },
    {
      "type": "documentDB",
      "name": "inputDocument",
      "databaseName": "admin",
      "collectionName": "aomsorders",
      "connection": "cdb-swm-dev-001_DOCUMENTDB",
      "direction": "in"
    },
    {
      "type": "documentDB",
      "name": "outputDocument",
      "databaseName": "admin",
      "collectionName": "test",
      "createIfNotExists": true,
      "connection": "cdb-swm-dev-001_DOCUMENTDB",
      "direction": "out"
    }
  ],
  "disabled": false
}

还更新了如下集成部件

enter image description here

任何建议都会很明显。

2 个答案:

答案 0 :(得分:1)

我发现你的问题不是很具体,但总的来说,你至少有两个选择:

  • 从同一个Azure功能

  • 插入两个集合
  • 从第一个Azure功能插入到集合1,然后使用第二个Azure功能Cosmos DB trigger监听集合1的更改并更新集合2

我确信还有其他选择。

答案 1 :(得分:0)

以下是由CosmosDBTrigger触发的Azure函数示例,然后使用DocumentDB输出绑定写入第二个集合:

<强> function.json

{
  "bindings": [
    {
      "type": "cosmosDBTrigger",
      "name": "input",
      "direction": "in",
      "databaseName": "your-database",
      "collectionName": "your-collection1",
      "connectionStringSetting": "name-of-connectionstring-setting-for-collection1",
      "leaseCollectionName": "your-lease-collection"
    },
    {
      "type": "documentDB",
      "direction": "out",
      "name": "docsToSave",
      "databaseName": "your-database2",
      "collectionName": "your-collection2",
      "connection": "name-of-connectionstring-setting-for-collection2",
      "createIfNotExists": false
    }
  ]
}

run.csx(C#)

#r "Microsoft.Azure.Documents.Client"
using Microsoft.Azure.Documents;
using System.Collections.Generic;
using System;
public static async Task Run(IReadOnlyList<Document> input, IAsyncCollector<Document> docsToSave)
{
    foreach(var doc in input){
        // Do something here, process the document or do your compute
        // Here I am saving the same document to the second collection but you could send a new document created within the processing logic or send the same document modified by some logic
        await docsToSave.AddAsync(doc);
    }
}

index.js(NodeJS)

module.exports = function(context, input) {
    if(!!input && input.length > 0){
        context.bindings.docsToSave = [];
        for(var i = 0, len=input.length; i<len;i++){
            var doc = input[i];
            // Do something here with the doc or create a new one
            context.bindings.docsToSave.push(doc);
        }
    }
    context.done();
}