首页 > 解决方案 > 选择 Cosmos DB 文档时展平对象

问题描述

我在 Cosmos DB 中有以下文档

{
  "id": "c6c7a79a-3351-8be8-2700-b0c9414c1622",
  "_rid": "mdRtAJiE1cEBAAAAAAAAAA==",
  "_self": "dbs/mdRtAA==/colls/mdRtAJiE1cE=/docs/mdRtAJiE1cEBAAAAAAAAAA==/",
  "_etag": "\"00000000-0000-0000-35f2-3baea11001d5\"",
  "FedId": "1023157382",
  "UniqueIdentifier": "00003089421",
  "UniqueIdentifierNumeric": 3089421,
  "Item": {
    "LastUpdatedDate": "2019-07-08T02:36:20",
    "OrderNumber": "2013282",
    "QueueRank": 2
  }
}

以及以下 C# 类

public class Item
{
    public string FedId { get; set; }
    public string UniqueIdentifier { get; set; }
    public DateTime LastUpdatedDate { get; set; }
    public string OrderNumber { get; set; }
    public int QueueRank { get; set; }
}

使用 Cosmos SQL API,如何选择文档并将其映射到Item类?

以下是我尝试过的:

var result = _client.CreateDocumentQuery<Item>(collectionLink, new SqlQuerySpec
{
    QueryText = @"
        SELECT c.FedId, c.UniqueIdentifier, i.*
        FROM c JOIN i IN c.Item
        WHERE
            sie.FedId = '1023157382'
    "
});

本质上,除了地图文档属性外,我还需要Item将 Cosmos 文档中的属性展平。我期待的结果是:

Console.WriteLine(result.FedId); // return "1023157382"
Console.WriteLine(result.UniqueIdentifier); // return "00003089421"
Console.WriteLine(result.LastUpdatedDate); // return "2019-07-08T02:36:20"
Console.WriteLine(result.OrderNumber); // return "2013282"
Console.WriteLine(result.QueueRank); // return 2

我也尝试过使用连接查询,但似乎不适用于非数组属性。 https://github.com/Azure/azure-cosmos-dotnet-v2/blob/d17c0ca5be739a359d105cf4112443f65ca2cb72/samples/code-samples/Queries/Program.cs#L421-L435

标签: c#azureazure-cosmosdbazure-cosmosdb-sqlapi

解决方案


DocumentDB 找到深层键:值

如果您没有数组属性,则不需要进行连接。你可以只使用c.Item.LastUpdatedDate.

结果应如下所示:

var result = _client.CreateDocumentQuery<Item>(collectionLink, new SqlQuerySpec
{
    QueryText = @"
        SELECT c.FedId, c.UniqueIdentifier, c.Item.LastUpdatedDate, c.Item.OrderNumber, c.Item.QueueRank
        WHERE
            c.FedId = '1023157382'
    "
});

另一方面,您也可以尝试使用 linq 提供程序。为您的顶级文档(例如MyDocument)和它的项目部分创建一个类,并使用它select来映射值。

会像这样工作:

var result = _client.CreateDocumentQuery<MyDocument>(collectionLink)
    .Select(document => new Item{
        FedId = document.FedId,
        UniqueIdentifier = document.FedId,
        LastUpdatedDate = document.Item.LastUpdatedDate,
        OrderNumber = document.Item.OrderNumber,
        QueueRank = document.Item.QueueRank
    });

PS:SelectMany一旦有了数组属性就使用,而不是编写 SQL 连接。


推荐阅读