我想使用 SQL API 查询来查询 Azure CosmosDb 文档。这些文档应按特定值进行过滤和分组。从这些组中,仅返回具有指定最大值的文档。
示例
Azure CosmosDb 文档
{
"id": "1",
"someValue": "shall be included",
"group": "foo",
"timestamp": "1668907312"
}
{
"id": "2",
"someValue": "shall be included",
"group": "foo",
"timestamp": "1668907314"
}
{
"id": "3",
"someValue": "shall be included",
"group": "bar",
"timestamp": "1668907312"
}
{
"id": "4",
"someValue": "don't include",
"group": "bar",
"timestamp": "1668907312"
}
查询
我想要获取所有文档
- 与
“someValue”:“应包含”
- 按
组
分组 - 仅来自组的最大
时间戳
响应示例
{
"id": "2",
"someValue": "shall be included",
"group": "foo",
"timestamp": "1668907314"
},
{
"id": "3",
"someValue": "shall be included",
"group": "bar",
"timestamp": "1668907312"
}
问题
执行此操作的最佳方法是什么?如果
,这将是最佳- 一次查询即可实现
- 并且可以通过 Azure SDK 执行 SqlParameter (防止注入(inject))
我尝试过的
我当前的方法由 2 个查询组成,并使用 ARRAY_CONTAINS
,它不允许使用 SqlParameter用于文档路径。
{
"id": "2",
"some-value": "shall be included",
"group": "foo",
"timestamp": "1668907314"
}
第一个查询
SELECT c.group AS group
MAX(c.timestamp) AS maxValue
FROM c
WHERE c.someValue = 'shall be included'
GROUP BY c.group
第二个查询
SELECT * FROM c WHERE ARRAY_CONTAINS(
<RESULT-FIRST-QUERY>,
{
"group": c.group,
"maxValue": c.timestamp
},
false
)
最佳答案
我会利用 MAX() function与 GROUP BY 结合使用,即
SELECT *
FROM c
WHERE c.someValue = "shall be included"
GROUP BY c.group
HAVING MAX(c.timestamp)
还没有运行/需要制作一个集合,但看起来它应该可以解决问题......
关于azure - 获取 CosmosDb 中分组文档的最大数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74530686/