Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DynamoDB Count Group By

We are trying to search a dynamodb, and need to get count of objects within a grouping, how can this be done?

I have tried this, but when adding the second number, this doesn't work:

$search = array(
    'TableName'     => 'dev_adsite_rating',
    'Select'        => 'COUNT',
    'KeyConditions' => array(
        'ad_id' => array(
            'ComparisonOperator' => 'EQ',
            'AttributeValueList' => array(
                array('N' => 1039722, 'N' => 1480)
            )
        )
    )
);
$response = $client->query($search);

The sql version would look something like this:

select ad_id, count(*) 
from dev_adsite_rating
where ad_id in(1039722, 1480)
group by ad_id;

So, is there a way for us to achieve this? I can not find anything on it.

like image 235
Get Off My Lawn Avatar asked Oct 31 '22 03:10

Get Off My Lawn


1 Answers

Trying to perform a query like this on DynamoDB is slightly trickier than in an SQL world. To perform something like this, you'll need to consider a few things

  1. EQ ONLY Hash Key: To perform this kind of query, you'll need to make two queries (i.e. ad_id EQ 1039722 / ad_id EQ 1480)
  2. Paginate through query: Because dynamodb returns your result set in increments, you'll need to paginate through your results. Learn more here.
  3. Running "Count": You can take the "Count" property from the response and add it to the running total as you're paginating through the results of both queries. Query API
like image 131
Raymond Lin Avatar answered Nov 13 '22 19:11

Raymond Lin