Search code examples
amazon-web-servicesamazon-dynamodbboto3

How do we query on a secondary index of dynamodb using boto3?


Is there a way at all to query on the global secondary index of dynamodb using boto3. I dont find any online tutorials or resources.


Solution

  • You need to provide an IndexName parameter for the query function.

    This is the name of the index, which is usually different from the name of the index attribute (the name of the index has an -index suffix by default, although you can change it during table creation). For example, if your index attribute is called video_id, your index name is probably video_id-index.

    import boto3
    from boto3.dynamodb.conditions import Key
    dynamodb = boto3.resource('dynamodb')
    table = dynamodb.Table('videos')
    video_id = 25
    response = table.query(
        IndexName='video_id-index',
        KeyConditionExpression=Key('video_id').eq(video_id)
    )
    

    To check the index name, go to the Indexes tab of the table on the web interface of AWS. You'll need a value from the Name column.