Skip to main content

DynamoDB Complex

Creating Table with Composite Key

To create a table with composite key, it is the same process, except you will be adding an additional field to the key-schema flag:

aws dynamodb create-table \
    --table-name UserOrdersTable \
    --attribute-definitions '[
        {
            "AttributeName": "Username",
            "AttributeType": "S"
        },
        {
            "AttributeName": "OrderId",
            "AttributeType": "S"
        }
    ]' \
    --key-schema '[
        {
            "AttributeName": "Username",
            "KeyType": "HASH"
        },
        {
            "AttributeName": "OrderId",
            "KeyType": "RANGE"
        }
    ]' \
    --provisioned-throughput '{
        "ReadCapacityUnits": 1,
        "WriteCapacityUnits": 1
    }' \
    $LOCAL

In addition, the KeyType must be of RANGE, you cannot have more than one HASH KeyType, it must be RANGE.

Retrieving All Items | Partition Key

If you want to query a list of items given a partition key for composite primary keys (because one partition key can map to multiple items with composite keys), you would need to use the query operation.

aws dynamodb query \
  --table-name UserOrdersTable \
  --key-condition-expression "Username = :usr" \
  --expression-attribute-values '{
      ":usr": {"S": "daffyduck"}
  }' \
  $LOCAL

get-item only works if you have the full key, in this case we are only giving it the partition key not the sorting key, hence it will not work.

Filtering

You can filter your result by your sorting key by using logical and built-in operators like below:

 

aws dynamodb query \
    --table-name UserOrdersTable \
    --key-condition-expression "Username = :usr AND OrderId BETWEEN :startdate AND :enddate" \
    --expression-attribute-values '{
        ":usr": {"S": "daffyduck"},
        ":startdate": {"S": "20170101"},
        ":enddate": {"S": "20180101"}
    }' \
    $LOCAL
Select

Every query operation will have the count key to show how many items were returned in the response. If you just want the count then you can include the --select COUNT option to return that.