amazon-web-servicesaws-lambdaamazon-dynamodbthroughputcapacity

Choose primary index for Global secondary index


I'm reading the AWS docs about secondary indices and I don't understand the following statement:

The index key does not need to have any of the key attributes from the table

From what I understand GSI allows me to create a primary or sort key on an attirubte in my table after its creation.

I would like to make sure I understand the statement above, does it mean exactly that I can create a primary or sort key on an attribute that is different from the current table's primary/hash key?


Solution

  • Yes, that is exactly what it means. Let's suppose that you have a table with a composite primary key that consists of bundle_id as the partition key and item_id as the sort key. Let's suppose you also have in that table an attribute called client_id.

    You can then create a GSI, let's call it client_id-index with client_id as its partition key and you can include some other attributes in the GSI too.

    Then you can query the GSI like this (code sample using Python and Boto3)

    table.query(
        IndexName='client_id-index',
        KeyConditionExpression=Key('client_id').eq("123456")
    )
    

    Please note that even if you specify ProjectionType as INCLUDE in your GSI and your include some non-key attributes, the key attributes from the table will be also included in your GSI.