azure - 获取 CosmosDb 中分组文档的最大数量

标签 azure azure-cosmosdb azure-cosmosdb-sqlapi azure-sdk-for-java

我想使用 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/

相关文章:

node.js - java.net.SocketInputStream.read(来源未知)处的连接重置 - Node.js - Azure 文件服务

c# - Azure Web 应用程序 - "HttpClient Unable to connect to the remote server"

azure - 跨资源组部署 Azure Functions

azure - 如何使用 AAD 身份验证在 powershell 中调用 Azure CosmosDB REST API

azure - 无法连接 CosmosDB 作为流分析输出

azure - 如何将 Xamarin 应用连接到 SQL Azure 数据库

c# - Azure DocumentDB异步请求问题

azure - 使用 COSMOSDB sql 查询的对象键的别名

c# - 如何(我应该)为 DocumentDb 单元测试模拟 DocumentClient?

azure - 如何在 CosmosDB 中使用 Join 操作/子查询