【问题标题】:How to read data from CosmosDb when i only have the partitionkey but not the id of the document当我只有 partitionkey 但没有文档的 id 时如何从 CosmosDb 读取数据
【发布时间】:2022-09-23 14:10:45
【问题描述】:

当尝试从 CosmosDb 读取时,我可以通过以下方式选择文档:

  • 身份证查询
  • Id + PartitionKey 查询

但是当我只有 PartitionKey 时,如何从 CosmosDb 中选择数据?

using Microsoft.Azure.Cosmos;
        
public class CosmosDbService : ICosmosDbService
{
    private Container _container;
    
    public CosmosDbService(
            CosmosClient cosmosDbClient,
            string databaseName,
            string containerName)
    {
        _container = cosmosDbClient.GetContainer(databaseName, containerName);
    }
    
    public async Task<Error> GetItemAsync(string partitionKey)
    {
        // selection only via partitionKey - does not work
        var response = await _container.ReadItemAsync<Error>(partitionKey, new PartitionKey(partitionKey));
        return response.Resource;

        // below one works as i am passing the Id (internally generated by CosmosDB)
        var id = \"2e4e5727-86ff-4c67-84a6-184b4716d744\";
        var response = await _container.ReadItemAsync<Error>(id, new PartitionKey(partitionKey));
        return response.Resource;
    }
}

问题: CosmosDB 客户端中是否还有其他方法可以仅使用 PartitionKey 返回文档而无需我不知道的 Id?

  • 您是将/customerId 作为输入传递给GetItemAsync 方法还是客户ID 的实际值。您需要传递实际值而不是分区键属性名称。
  • 是的,我正在传递 CustomerId 值
  • 因此,当您将partitionKey 传递为2e4e5727-86ff-4c67-84a6-184b4716d744 时,您不会得到任何数据。那是对的吗?
  • 我正在尝试使用“CustomerId”获取记录,但它不会返回数据,除非我同时传递“Id-->csomosDB 内部生成”和作为分区键的 CustomerId
  • 要读取单个项目,您需要同时传递文档 ID 和分区键值。

标签: azure-cosmosdb


【解决方案1】:

选择文档时,您可以尝试使用 QueryDefinition + QueryAsync:

var query = new QueryDefinition("select top 1 * from c");
var partitionKey = "PARTITIONKEY";
var resultSet = container.GetItemQueryIterator<ModelObject>(query, null, new QueryRequestOptions { PartitionKey = new PartitionKey(partitionKey) });
var result = new List<ModelObject>();

while (resultSet.HasMoreResults)
{
    var item = await resultSet.ReadNextAsync(ct /* CancellationToken */).ConfigureAwait(false);
    var itemList = item.ToList();
    result.AddRange(itemList);
}

除了 top 1 选择,您还可以选择 * (例如)

【讨论】:

  • 谢谢斯蒂芬。几个问题 1. var partitionKey = "ID OF PARTITION";,您的意思是 Partitionkey 的值,例如,如果我想获取 customerId =C0001 的记录,我应该在 partitionkey 变量中分配“C0001”:返回值是什么结果([0]。2)传递给ReadNextAsync的“ct”是什么?
  • @novice8989 是的 partitionkey 值。结果将是与查询匹配的所有对象的列表。 ct 是一个 CancellationToken。如果您在没有 CancellationToken 的情况下调用它,只需使用 CancellationToken.None。您的代码的问题是您从值为“xyz”的分区中进行选择,并希望检索 id 值为“xyz”的文档。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-01-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多