使用 readItems(queryString) 通过查询对项目进行计数

Count items with query using readItems(queryString)

我想统计容器中的物品数量。

使用 SELECT value count(1) FROM tasks WHERE tasks.TaskState = 0 OR (tasks.TaskState = 4 AND tasks.RetryCount <= 3) 在 Azure 门户上工作,现在我想在服务器端做同样的事情。

我尝试这样做,但这不起作用...

await this.Container.RetrieveItemsAsync<int>(new Query(CreateNumberOfTasksQuery()), cancellationToken: cancellationToken).ConfigureAwait(false);

我的查询是:

"SELECT value count(1) FROM tasks WHERE tasks.TaskState = 0 OR (tasks.TaskState = 4 AND tasks.RetryCount <= 3)";

我无法检索该项目,因为 int 不是参考类型...

实施class:

public async Task<IList<T>> RetrieveItemsAsync<T>(Query query, QueryOptions queryOptions = null, CancellationToken cancellationToken = default)
    where T : class
{
    // Validation

    SmartGuard.Check(() => query, typeof(T) != typeof(string), Properties.Resources.RES_Exception_MultiModel_Argument_UnsupportedType.Format(typeof(string)));
    SmartGuard.NotNull(() => query, query);

    // Logging

    this.Service.Logger.LogDebug($"Retrieving items...");

    // Delegate on instance
    // Make sure the exceptions handler is called

    IList<T> result = await CosmosDbMultiModelDatabaseExceptionHandler.HandleAsync(
        OperationTarget.Item,
        async () =>
        {
            IList<T> result = new List<T>();

            Cosmos.FeedIterator<T> feedIterator = this.Instance.GetItemQueryIterator<T>(
                queryDefinition: query.ToQueryDefinition(),
                requestOptions: queryOptions.ToQueryRequestOptions());

            while (feedIterator.HasMoreResults)
            {
                foreach (T item in await feedIterator.ReadNextAsync(cancellationToken).ConfigureAwait(false))
                {
                    result.Add(item);
                }
            }

            return result;
        })
        .ConfigureAwait(false);

    // Logging

    this.Service.Logger.LogDebug($"{result.Count} items were retrieved.");

    // Result

    return result;
}

这是因为where T : class限制你的类型必须是引用类型。

您可以重载您的 RetrieveItemsAsync 方法,

public async Task<IList<T>> RetrieveItemsAsync<T>(T value,Query query, QueryOptions queryOptions = null, CancellationToken cancellationToken = default)
    where T : struct
{
.....
}

那你可以试试这个:

await this.Container.RetrieveItemsAsync<int>(Int32.MaxValue,new Query(CreateNumberOfTasksQuery()), cancellationToken: cancellationToken).ConfigureAwait(false);