How to get item count from DynamoDB?

前端 未结 12 2247
故里飘歌
故里飘歌 2020-12-04 17:15

I want to know item count with DynamoDB querying.

I can querying for DynamoDB, but I only want to know \'total count of item\'.

For example, \'SELECT COUNT(*

12条回答
  •  醉梦人生
    2020-12-04 17:51

    I'm posting this answer for anyone using C# that wants a fully functional, well-tested answer that demonstrates using query instead of scan. In particular, this answer handles more than 1MB size of items to count.

            public async Task GetAvailableCount(string pool_type, string pool_key)
        {
            var queryRequest = new QueryRequest
            {
                TableName = PoolsDb.TableName,
                ConsistentRead = true,
                Select = Select.COUNT,
                KeyConditionExpression = "pool_type_plus_pool_key = :type_plus_key",
                ExpressionAttributeValues = new Dictionary {
                    {":type_plus_key", new AttributeValue { S =  pool_type + pool_key }}
                },
            };
            var t0 = DateTime.UtcNow;
            var result = await Client.QueryAsync(queryRequest);
            var count = result.Count;
            var iter = 0;
            while ( result.LastEvaluatedKey != null && result.LastEvaluatedKey.Values.Count > 0) 
            {
                iter++;
                var lastkey = result.LastEvaluatedKey.Values.ToList()[0].S;
                _logger.LogDebug($"GetAvailableCount {pool_type}-{pool_key} iteration {iter} instance key {lastkey}");
                queryRequest.ExclusiveStartKey = result.LastEvaluatedKey;
                result = await Client.QueryAsync(queryRequest);
                count += result.Count;
            }
            _logger.LogDebug($"GetAvailableCount {pool_type}-{pool_key} returned {count} after {iter} iterations in {(DateTime.UtcNow - t0).TotalMilliseconds} ms.");
            return count;
        }
    }
    

提交回复
热议问题