我有以下课程:
public class RetailProduct
{
public string OriginalVersionId { get; set; }
public string Version { get; set; }
public DateTime AvailableTo { get; set; }
}
以及以下查询:
public async Task<PagedResponse<RetailProduct>> GetAllRetailProducts(string continuationToken, int pageSize = 10)
{
var feedOptions = new FeedOptions
{
MaxItemCount = pageSize,
RequestContinuation = continuationToken
};
Uri collectionUri = UriFactory.CreateDocumentCollectionUri(_databaseName, _retailProductCollectionName);
IDocumentQuery<RetailProduct> query = _client.CreateDocumentQuery<RetailProduct>(collectionUri, feedOptions)
.GroupBy(g => g.OriginalVersionId)
.Select(p => p.OrderByDescending(x => x.Version))
.Select(p => p.FirstOrDefault())
.Where(r => r.AvailableTo > DateTime.UtcNow || r.AvailableTo == null)
.AsDocumentQuery();
if (query.HasMoreResults)
{
FeedResponse<RetailProduct> products = await query.ExecuteNextAsync<RetailProduct>();
return new PagedResponse<RetailProduct>()
{
Continuation = products.ResponseContinuation,
Results = products.ToList()
};
}
return null;
}
上述方法将失败,因为我试图在GroupBy
中执行CosmosDB
。如果按照以下方式进行更改,则将其分组in-memory
,我将得到结果:
public async Task<PagedResponse<RetailProduct>> GetAllRetailProducts(string continuationToken, int pageSize = 10)
{
var feedOptions = new FeedOptions
{
MaxItemCount = pageSize,
RequestContinuation = continuationToken
};
Uri collectionUri = UriFactory.CreateDocumentCollectionUri(_databaseName, _retailProductCollectionName);
IDocumentQuery<RetailProduct> query = _client.CreateDocumentQuery<RetailProduct>(collectionUri, feedOptions).AsDocumentQuery();
if (query.HasMoreResults)
{
FeedResponse<RetailProduct> products = await query.ExecuteNextAsync<RetailProduct>();
var filteredList = products.ToList()
.GroupBy(g => g.OriginalVersionId)
.Select(p => p.OrderByDescending(x => x.Version))
.Select(p => p.FirstOrDefault())
.Where(r => r.AvailableTo > DateTime.UtcNow || r.AvailableTo == null);
return new PagedResponse<RetailProduct>()
{
Continuation = products.ResponseContinuation,
Results = filteredList
};
}
return null;
}
问题是,由于我正在对数据进行“内存中”操作,由于我的过滤,返回的数据集不再总是包含10条记录。
我唯一想到的另一种选择是递归调用我的函数,直到结果包含10个过滤的记录,然后返回,但这会消耗很多RU's
并变得非常昂贵。
我错过了什么吗,我还能采取另一种方法吗?