在cosmos DB中创建分区键时出现以下错误。
执行功能时发生异常:SetUserSubscriptions-> Cross 分区查询是必需的,但已禁用。请设定 x-ms-document-db-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;
}
答案 0 :(得分:1)
如comment中所述,您需要使用以下Feed选项启用 Cross partition query
,
var criteria = client.CreateDocumentQuery<T>(
UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId),new FeedOptions { EnableCrossPartitionQuery=true})
答案 1 :(得分:0)
当我添加new FeedOptions { EnableCrossPartitionQuery=true}
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),new FeedOptions { EnableCrossPartitionQuery=true})
.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;
}