I need help with querying a DynamoDB table to get the count of rows.
Consider, I have a table “Users” with three fields, “UserName”, “Password” and “UserType”. UserType can be “Admin”, “Employee” or @”Guest”. Now I want to get the count of “Admin” in the table. In SQL we write the query like this,
SELECT COUNT(*) FROM Users WHERE UserType='Admin'
Now I need to do the same using DynamoDB iOS SDK. For now, I am doing it like this.
- (int)adminUsersCount {
DynamoDBScanRequest *request = [[[DynamoDBScanRequest alloc] initWithTableName:@"Users"] autorelease];
DynamoDBCondition *condition = [[[DynamoDBCondition alloc] init] autorelease];
NSMutableArray *attrList = [NSMutableArray arrayWithObject:[[[DynamoDBAttributeValue alloc] initWithS:@"Admin"]] autorelease]];
condition.attributeValueList = attrList;
condition.comparisonOperator = @"EQ";
[request setScanFilterValue:condition forKey:@"UserType"];
DynamoDBScanResponse *response = [[AmazonClientManager ddb] scan:request];
return response.items.count;
}
Here I am fetching all the rows to know that count. I know this is not the right way and is really a bad idea. I don’t know how to get the count alone without fetching all the rows.
- I want to know how to do it in iOS SDK.
- I want to know how to do it in PHP SDK as well.
Thanks.
I can not answer for PHP nor IOS SDK since I use neither of them (I use Python). But, from a low level DynamoDB point of view:
ItemCountfromDescribeTable. It is updated only every 6 hours but it’s freeUserTypeis therange_key(excelent), you can setCountparam ofQuerytoTruethen readCountfield of the answer.Queryalong with your filter condition.This said,
QueryandScanwill always return the the item count. TheCountparam only instruct them not to return the real items. Please note that it only spares bandwidth. It won’t be any faster nor be cheaper in terms of provisioned throughput.If you are in the 3rd case, I suggest you re-engineer your you schema as it would be very slow and expensive. At all requests, you will need to go through the entire table.