【问题标题】:Querying CosmosDB Child Collection using ORDER BY使用 ORDER BY 查询 CosmosDB 子集合
【发布时间】:2021-12-18 04:06:21
【问题描述】:

假设我对每个 userId 都有一个如下所示的文档。每个 userId 都有一个名为“lnk”的子集合对象,每个 userId 最多可以增长 100 个项目。

我想根据单个属性对给定 userId 的子集合进行排序 (例如:主题或 Pid 或 URL)。对于用户 ID =“5663a8f7-6d2e-40ef-8972-515944080474”

SELECT * FROM c IN PageLinksContainer.lnk order by c.top asc OFFSET 1 LIMIT  3

我得到的错误:

Failed to query item for container PageLinksContainer:
{
  "errors": [
    {
      "severity": "Error",
      "location": {
        "start": 7,
        "end": 25
      },
      "code": "SC2001",
      "message": "Identifier 'PageLinksContainer' could not be resolved."
    },
    {
      "severity": "Error",
      "location": {
        "start": 67,
        "end": 85
      },
      "code": "SC2001",
      "message": "Identifier 'PageLinksContainer' could not be resolved."
    }
  ]
} 
{
    "userid": "5663a8f7-6d2e-40ef-8972-515944080474",
    "lnk": [
        {
            "pid": 1,
            "top": "Topic 1",
            "por": "www.google.com",
            "sdt": "10/26/2021"
        },
        {
            "pid": 2,
            "top": "Topic 2",
            "por": "www.google.com",
            "sdt": "10/26/2021"
        },
        {
            "pid": 3,
            "top": "Topic 3",
            "por": "www.google.com",
            "sdt": "10/26/2021"
        }
    ]
}

C#

 var query = "SELECT * FROM c IN PageLinksContainer.lnk OFFSET 1 LIMIT  10"; //Works fine with no order by.

 var container = _cosmosClient.GetContainer(_databaseName, containerName);

 using var iterator = container.GetItemQueryStreamIterator(new QueryDefinition(query),
                requestOptions: new QueryRequestOptions
                {
                    PartitionKey = new PartitionKey("5663a8f7-6d2e-40ef-8972-515944080474"),
                    MaxItemCount = 100
                });

链接:

https://docs.microsoft.com/en-us/azure/cosmos-db/sql/sql-query-order-by

CosmosDB sql query with/without "ORDER BY" returns different number of items

【问题讨论】:

    标签: c# azure-cosmosdb azure-cosmosdb-sqlapi


    【解决方案1】:

    您目前不能ORDER BY 数组中的属性。

    以下查询更好地证明了以下错误Order-by over correlated collections is not supported

    SELECT VALUE l
    FROM c
    JOIN l IN c.lnk
    ORDER BY l.por
    

    您可以做的是创建一个用户定义函数,在返回之前对数组进行排序。虽然我建议您检索结果并在 C# 代码中使用 OrderBy,因为它更容易、更透明,并且避免在 UDF 上花费不必要的 RU。

    【讨论】:

    • 你是对的。我在想同样得到 100 个结果并在 C# 中使用 order by 我可以很容易地做到这一点。谢谢。顺便说一句-由于我没有足够的声誉,我无法为您的答案投票。我稍后再做。
    猜你喜欢
    • 2022-11-02
    • 1970-01-01
    • 2014-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多