【发布时间】:2020-03-04 08:43:12
【问题描述】:
在 cosmos DB 中创建分区键时出现以下错误。
执行函数时出现异常:SetUserSubscriptions -> Cross 分区查询是必需的,但已禁用。请设置 x-ms-documentdb-query-enablecrosspartition 为 true,指定 x-ms-documentdb-partitionkey,或修改您的查询以避免这种情况 异常。\r\nActivityId: 4685a5b7-bce9-4855-b2d8-33353f2957d9, Microsoft.Azure.Documents.Common/2.2.0.0、documentdb-dotnet-sdk/2.1.3 主机/32位MicrosoftWindowsNT/6.2.9200.0"
这是我的代码:
public static async Task<IEnumerable<T>> GetItemsAsync(Expression<Func<T, bool>> predicate, Expression<Func<T, object>> orderByDesc,int takeCount =-1)
{
;
var criteria = client.CreateDocumentQuery<T>(
UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId))
.Where(predicate)
.OrderByDescending(orderByDesc)
.AsDocumentQuery();
IDocumentQuery<T> query = criteria;
List<T> results = new List<T>();
while (query.HasMoreResults)
{
if (takeCount>-1 && results.Count >= takeCount)
{
break;
}
results.AddRange(await query.ExecuteNextAsync<T>());
}
return results;
}
private static async Task CreateCollectionIfNotExistsAsync()
{
try
{
await client.ReadDocumentCollectionAsync(
UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId));
}
catch (DocumentClientException e)
{
if (e.StatusCode == System.Net.HttpStatusCode.NotFound)
{
await client.CreateDocumentCollectionAsync(
UriFactory.CreateDatabaseUri(DatabaseId),
new DocumentCollection
{
Id = CollectionId,
IndexingPolicy = new IndexingPolicy(new RangeIndex(DataType.String) { Precision = -1 }),
PartitionKey = new PartitionKeyDefinition { Paths = new System.Collections.ObjectModel.Collection<string> { GetPartitionKeyAttributeCosmoDbCollection(typeof(T)) } }
},
new RequestOptions { OfferThroughput = 1000 });
}
else
{
throw;
}
}
}
public static string GetPartitionKeyAttributeCosmoDbCollection(Type t)
{
// Get instance of the attribute.
CosmoDbCollection attribute =
(CosmoDbCollection)Attribute.GetCustomAttribute(t, typeof(CosmoDbCollection));
if (attribute == null)
{
throw new Exception("The attribute CosmoDbCollection was not found.");
}
return attribute.PartitionKey;
}
【问题讨论】:
-
你能添加堆栈跟踪吗?我在您的代码中没有看到任何会产生该错误的查询。
-
另外,还有一个 CreateCollectionIfNotExists:docs.microsoft.com/en-us/dotnet/api/…
标签: azure-cosmosdb azure-cosmosdb-sqlapi