在Azure Functions中,以代码

时间:2019-04-17 04:39:33

标签: azure azure-functions azure-cosmosdb

我可以在代码本身中运行Cosmos DB查询吗?我现在所能做的就是在代码运行(输入)之前运行查询。我需要首先运行一些代码,然后在cosmos DB中获取数据。我该如何使用JavaScript?

2 个答案:

答案 0 :(得分:0)

您可以参考此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
}

功能代码:

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();
};

请注意:以上代码适用于Azure Function V1 binding configuration

enter image description here

答案 1 :(得分:0)

使用输入绑定时,pull in the DocumentClient有一个选项(但仅用于C#),可用于运行任何查询或操作。

如果约束条件是在JavaScript上运行的,那么您当然可以直接在函数中使用Cosmos DB JS SDK,而不是像下面这样使用Input Binding:

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_URLCOSMOS_API_KEY应该是指向Azure Cosmos帐户终结点和主密钥的环境变量。您可以根据需要用查询替换数据库,容器和修补程序的名称。