Azure函数App HTTP触发器CosmosDB输入查询来自请求的正文

人气:445 发布:2022-10-16 标签: azure azure-functions azure-cosmosdb

问题描述

我已创建一个Azure函数,该函数由HTTP POST请求触发。 该请求的正文如下:

{
    "start": '2018-07-25T08:47:16.094Z',
    "end": '2018-07-25T08:47:24.686Z'
}

index.js

module.exports = async function (context, req) {
    context.log('JavaScript HTTP trigger function processed a request.');

    var inputDocument = context.bindings.inputDocument;
    context.log("INPUT DOCUMENT: " + JSON.stringify(inputDocument));
    context.res = {
            status: 200,
            body: "OK",
        };
};

函数.json

{
  "bindings": [
    {
      "authLevel": "function",
      "type": "httpTrigger",
      "direction": "in",
      "name": "req",
      "methods": [
        "post"
      ]
    },
    {
      "type": "http",
      "direction": "out",
      "name": "res"
    },
    {
      "type": "cosmosDB",
      "name": "inputDocument",
      "databaseName": "Messages",
      "collectionName": "Collection1",
      "sqlQuery": "SELECT * FROM Collection1 c WHERE c.message.timestamp>={start} AND c.message.timestamp<={end}",
      "connectionStringSetting": "cosmosdbaccount_DOCUMENTDB",
      "direction": "in"
    }
  ]
}

我想用以下两个参数查询CosmosDB实例:

"sqlQuery": "SELECT * FROM Collection1 c WHERE c.message.timestamp>={start} AND c.message.timestamp<={end}",

按此处所示操作会导致CosmosDB的inputBinding未定义。

2018-12-13T08:19:54.332 [Information] Executing 'Functions.Function1' (Reason='This function was programmatically called via the host APIs.', Id=af8090a4-5fab-4fbd-b26f-a045d8900d9b)
2018-12-13T08:19:56.704 [Information] JavaScript HTTP trigger function processed a request.
2018-12-13T08:19:56.711 [Information] INPUT DOCUMENT: []
2018-12-13T08:19:56.755 [Information] Executed 'Functions.Function1' (Succeeded, Id=af8090a4-5fab-4fbd-b26f-a045d8900d9b)

如果我运行相同的查询,在CosmosDB数据资源管理器中用正确的ISO时间戳替换startend,它将返回所有四个文档。

我错过了什么吗?我真的没有在网上找到任何关于这个话题的东西,所以我希望有人已经偶然发现了它。

提前感谢!

推荐答案

目前似乎预期结果为空。在CosmosDB绑定中,sqlQuery难以处理嵌套令牌(startend是请求体的属性),related issue here。

这里有三个可以尝试的解决方法。

只需将startend放在查询字符串中,如https://functionUrl?start=<timeA>&end=<timeB>

function.json中设置路由参数startend,即在HTTrigger绑定中添加"route": "{start}/{end}",。然后在URL中输入要访问的时间。

获取请求正文并自行获取query CosmosDB。

972