0

我有以下课程:

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;
    }

上面的方法会失败,因为我正在尝试做一个GroupByin 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并且变得非常昂贵。

我错过了什么,我可以采取另一种方法吗?

4

0 回答 0