Cosmos DB 3.37.1:分区键不匹配异常问题求助
Cosmos DB分区键不匹配异常原因及解决
问题描述
反复遇到Cosmos DB分区键不匹配异常,相关代码如下:
创建容器代码
string partitionKeyPath = $"/{_userId}"; _container = await database.CreateContainerIfNotExistsAsync(_containerName, partitionKeyPath);
添加Chat对象代码
if (_container != null) { Chat? chat; bool newChatCreated = false; try { // 尝试读取Chat项,存在则添加ChatItem chat = await _container.ReadItemAsync<Chat>(chatId, new PartitionKey(_userId)).ConfigureAwait(false); } catch (CosmosException ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound) { // 不存在则创建新Chat chat = new Chat { id = chatId, _userId = _userId, ChatItems = new List<ChatItem>(), ChatName = chatName, IndexName = indexName, TimeCreated = DateTime.Now.ToString("yyyy/MM/dd-HH:mm:ss.fff") }; ContainerProperties props = await _container.ReadContainerAsync(); _logger.LogInformation($"PartitionKeyPath: {props.PartitionKeyPath}"); // 异常发生在CreateItemAsync这一行 await _container.CreateItemAsync<Chat>(chat, new PartitionKey(_userId)); newChatCreated = true; } chat?.ChatItems?.Add(chatItem); if (newChatCreated) { // 更新数据库中的Chat项 await _container.ReplaceItemAsync<Chat>(chat, chatId, new PartitionKey(_userId)); } else { var patchOperations = new List<PatchOperation> { PatchOperation.Add("/ChatItems/-", chatItem) }; await _container.PatchItemAsync<Chat>(chatId, new PartitionKey(_userId), patchOperations); } } else { _logger.LogError("_container is null"); return false; }
已知用作分区键的_userId值为supportgpt4officecom,已验证容器的分区键路径为/supportgpt4officecom,使用Microsoft.Azure.CosmosDB 3.37.1版本。
异常原因
核心错误出在容器创建时的分区键路径配置:
你把具体的_userId值(supportgpt4officecom)当成了分区键的属性名,设置了$"/{_userId}"作为路径。但Chat对象中存储分区键值的属性是_userId,Cosmos DB会根据分区键路径去对象里找对应名称的属性——此时它会找名为supportgpt4officecom的属性,而不是_userId,自然无法提取到分区键值,因此抛出分区键不匹配异常。
解决办法
创建容器时,分区键路径应该指向Chat对象中的属性名,而非具体属性值,修正代码如下:
// 正确的分区键路径:指向Chat对象的_userId属性 string partitionKeyPath = "/_userId"; _container = await database.CreateContainerIfNotExistsAsync(_containerName, partitionKeyPath);
修正后,Cosmos DB会正确从Chat对象的_userId属性中提取分区键值,和你传入new PartitionKey(_userId)的参数匹配,异常即可解决。
内容的提问来源于stack exchange,提问作者Leon
相关产品推荐
相关产品推荐

